public void ConnectAsync() { Connection = new HubConnection("http://54.69.68.144:8733/signalr"); HubProxy = Connection.CreateHubProxy("ChatHub"); //Handle incoming event from server: use Invoke to write to console from SignalR's thread HubProxy.On<string>("AddMessage", (msg) => Console.WriteLine("AddMessage Call: " + msg) ); HubProxy.On<string>("GetAllMessage", (s) => Console.WriteLine(String.Format("{0}: {1}", Environment.NewLine, s)) ); HubProxy.On<int>("GetNumberOfUsers",(s) => Console.WriteLine(s) ) ; try { Connection.Start().Wait(); } catch (HttpRequestException) { Console.WriteLine("Unable to connect to server: Start server before connecting clients."); } //HubProxy.Invoke("GetAllMessages"); //await HubProxy.Invoke("GetNumberOfUsers"); }
/* Constructor for page */ public MainPage() { // Initialize the component model InitializeComponent(); // Set the data context for the page bindings DataContext = App.ViewModel; // Create speech recognizer _Recognizer = new SpeechRecognizerUI(); // Bind up shake gesture ShakeGesturesHelper.Instance.ShakeGesture += new EventHandler<ShakeGestureEventArgs>(Instance_ShakeGesture); ShakeGesturesHelper.Instance.MinimumRequiredMovesForShake = 4; ShakeGesturesHelper.Instance.Active = true; // Create demo recognizer and set grammer _DemoRecognizer = new SpeechRecognizerUI(); _DemoRecognizer.Recognizer.Grammars.AddGrammarFromList("Demo", App.GrammerList); // Create speech synthesizer _Synthesizer = new SpeechSynthesizer(); // Create signalr connection _Connection = new HubConnection("http://sagevoice.azurewebsites.net/"); _Connection.StateChanged += change => ReportChange(change); // Create hub proxy _Hub = _Connection.CreateHubProxy("erpTicker"); _Hub.On<string>("addResponse", data => OnResponse(data)); }
async void Hookup() { var deviceName = ConfigurationManager.AppSettings["DeviceName"]; CurrentDevice = PTZDevice.GetDevice(deviceName, PTZType.Relative); var url = ConfigurationManager.AppSettings["relayServerUrl"]; var remoteGroup = Environment.MachineName; //They have to hardcode the group, but for us it's our machine name var connection = new HubConnection(url); var proxy = connection.CreateHubProxy("RelayHub"); proxy.On<int, int>("Move", (x, y) => { Console.WriteLine("Move({0},{1})", x, y); BoxContext.Log.DebugFormat("Move({0},{1})", x, y); CurrentDevice.Move(x, y); }); proxy.On<int>("Zoom", (z) => { Console.WriteLine("Zoom ({0})", z); BoxContext.Log.DebugFormat("Zoom ({0})", z); CurrentDevice.Zoom(z); }); try { await connection.Start(); BoxContext.Log.DebugFormat("After connection.Start()"); await proxy.Invoke("JoinRelay", remoteGroup); BoxContext.Log.DebugFormat("After JoinRelay"); BoxContext.Log.DebugFormat("Joined remote group - " + remoteGroup); } catch (Exception pants) { BoxContext.Log.ErrorFormat(pants.GetError().ToString()); throw; } }
public MainWindow() { InitializeComponent(); connection = new HubConnection("http://localhost:9081/"); var messageOverviewHub = connection.CreateHubProxy("MessageOverviewHub"); connection.StateChanged += change => { Console.WriteLine(change.OldState + " => " + change.NewState); var connectionState = change.NewState; switch (connectionState) { case ConnectionState.Connecting: break; case ConnectionState.Connected: break; case ConnectionState.Reconnecting: break; case ConnectionState.Disconnected: Connect(); break; default: throw new ArgumentOutOfRangeException(); } }; messageOverviewHub.On<MessageUpdated>("invoke", i => label1.Content = string.Format("Message was updated at {0} ", i.Time)); this.Loaded +=OnLoaded; }
private async void Init() { hubConnection = new HubConnection("http://localhost:5225"); proxy = hubConnection.CreateHubProxy("MyHub"); await hubConnection.Start(); proxy.On<string>("executeCommand", (data) => { Debug.WriteLine(data); // var message = Newtonsoft.Json.JsonConvert.DeserializeObject<Message>(data.ToString()); }); qmhubConnection = new HubConnection("http://quantifymewebhub.azurewebsites.net/"); qmproxy = qmhubConnection.CreateHubProxy("QuantifyMeHub"); await qmhubConnection.Start(); qmproxy.On<string,string>("send", (name, data) => { Debug.WriteLine(data); var message = new Message { Source = "RemoteUWP", Action = "UpdateData", Value = data }; proxy.Invoke("Send", Newtonsoft.Json.JsonConvert.SerializeObject(message)); }); }
private async void ActionWindowLoaded(object sender, RoutedEventArgs e) { if (count == 0) { id = Properties.Settings.Default.UserID; //ClientNameTextBox.Text = id; Active = true; Thread = new System.Threading.Thread(() => { Connection = new HubConnection(Host); Proxy = Connection.CreateHubProxy("SignalRMainHub"); Proxy.On<string, string>("addmessage", (name, message) => OnSendData(DateTime.Now.ToShortTimeString()+" ["+ name + "]\t " + message)); Proxy.On("heartbeat", () => OnSendData("Recieved heartbeat <3")); Proxy.On<HelloModel>("sendHelloObject", hello => OnSendData("Recieved sendHelloObject " + hello.Molly + " " + hello.Age)); Connection.Start(); while (Active) { System.Threading.Thread.Sleep(10); } }) { IsBackground = true }; Thread.Start(); count++; } }
static void Main(string[] args) { var hub = new HubConnection("http://localhost:20133"); IHubProxy client = hub.CreateHubProxy("SelfHub"); client.On<UserMessage>("addmessage", (msg) => Console.WriteLine("{0} : {1}", msg.Source,msg.Message)); hub.Start().Wait(); Console.WriteLine("Enter your name, then [enter]"); var user = Console.ReadLine() ?? "guest"; client["user"] = user; string line = null; while ((line = Console.ReadLine()) != null) { client.Invoke("Send", new UserMessage(user,line)).ContinueWith( task => { if(task.IsFaulted) Console.WriteLine("ERR : {0}",task.Exception.GetBaseException()); else Console.WriteLine("OK...Sent"); }); } }
public IHubProxy Create(string hubUrl, Action<IHubConnection> configureConnection, Action<IHubProxy> onStarted, Action reconnected, Action<Exception> faulted, Action connected) { var connection = new HubConnection(hubUrl); if (configureConnection != null) configureConnection(connection); var proxy = connection.CreateHubProxy("EventAggregatorProxyHub"); connection.Reconnected += reconnected; connection.Error += faulted; Task.Factory.StartNew(() => { try { connection.Start().Wait(); onStarted(proxy); connected(); } catch (Exception ex) { faulted(ex); } }); return proxy; }
private static void ConnectEventHub() { hubConnection = new HubConnection(connectionUrl); proxy = hubConnection.CreateHubProxy("EventHub"); hubConnection.Start().Wait(); connected = true; }
public App() { InitializeComponent(); var label = new Label(); var button = new Button() { Text = "送信", }; conn = new HubConnection("http://localhost:5000"); proxy = conn.CreateHubProxy("hello"); proxy.On<string>("helloWorld", x => { label.Text = x; }); conn.Start(); button.Clicked += OnClick; var stack = new StackLayout() { Orientation = StackOrientation.Vertical, }; stack.Children.Add(label); stack.Children.Add(button); MainPage = new ContentPage() { Content = stack, }; }
private void RunHubConnectionAPI(string url) { var hubConnection = new HubConnection(url); hubConnection.TraceWriter = _traceWriter; var hubProxy = hubConnection.CreateHubProxy("HubConnectionAPI"); hubProxy.On<string>("displayMessage", (data) => hubConnection.TraceWriter.WriteLine(data)); hubConnection.Start().Wait(); hubConnection.TraceWriter.WriteLine("transport.Name={0}", hubConnection.Transport.Name); hubProxy.Invoke("DisplayMessageCaller", "Hello Caller!").Wait(); string joinGroupResponse = hubProxy.Invoke<string>("JoinGroup", hubConnection.ConnectionId, "CommonClientGroup").Result; hubConnection.TraceWriter.WriteLine("joinGroupResponse={0}", joinGroupResponse); hubProxy.Invoke("DisplayMessageGroup", "CommonClientGroup", "Hello Group Members!").Wait(); string leaveGroupResponse = hubProxy.Invoke<string>("LeaveGroup", hubConnection.ConnectionId, "CommonClientGroup").Result; hubConnection.TraceWriter.WriteLine("leaveGroupResponse={0}", leaveGroupResponse); hubProxy.Invoke("DisplayMessageGroup", "CommonClientGroup", "Hello Group Members! (caller should not see this message)").Wait(); hubProxy.Invoke("DisplayMessageCaller", "Hello Caller again!").Wait(); }
private static void Connect() { analyticsWebsiteExceptionHubConnection = new HubConnection(analyticsWebsiteConnectionUrl); analyticsWebsiteProxy = analyticsWebsiteExceptionHubConnection.CreateHubProxy("ExceptionHub"); analyticsWebsiteExceptionHubConnection.Start().Wait(); analyticsWebsiteConnected = true; }
public CoordinateHubClient(Action<Coordinate> callback) { _hubConnection = new HubConnection("http://indoorgps.azurewebsites.net"); _hubProxy = _hubConnection.CreateHubProxy("CoordinateHub"); _hubProxy.On<Coordinate>("SendNewCoordinate", callback); _hubConnection.Start().Wait(); }
public Bot(string url, string name, string password) { Name = name; _connection = new HubConnection(url); _connection.CookieContainer = this.BuildCookieContainer(url + "/account/login", name, password); _chat = _connection.CreateHubProxy("Chat"); }
partial void Application_Initialize() { HubConnection hubConnection; http://localhost:49499 hubConnection = new HubConnection("http://localhost:49499"); //make sure it matches your port in development // HubProxy = hubConnection.CreateProxy("MyHub"); HubProxy = hubConnection.CreateHubProxy("Chat"); HubProxy.On<string, string>("CustomersInserted", (r, user) => { this.ActiveScreens.First().Screen.Details.Dispatcher.BeginInvoke(delegate() { this.ActiveScreens.First().Screen.ShowMessageBox("han creat un client"); }); // this.Details.Dispatcher.BeginInvoke(() => // { // this.ActiveScreens.First().Screen.ShowMessageBox("han creat un client"); //// Console.WriteLine("Han creat un client"); // }); }); HubProxy.On<string>("addMessage", (missatge) => { this.ActiveScreens.First().Screen.Details.Dispatcher.BeginInvoke(delegate() { this.ActiveScreens.First().Screen.ShowMessageBox("has rebut un "+missatge); }); // this.Details.Dispatcher.BeginInvoke(() => // { // this.ActiveScreens.First().Screen.ShowMessageBox("han creat un client"); //// Console.WriteLine("Han creat un client"); // }); }); hubConnection.Start().Wait(); }
private static void Connect() { _hubConnection = new HubConnection(ConnectionUrl); _proxy = _hubConnection.CreateHubProxy("chat"); _hubConnection.Start().Wait(); _connected = true; }
public async Task WebSocketSendReceiveTest() { const int MessageCount = 3; var sentMessages = new List<string>(); var receivedMessages = new List<string>(); using (var hubConnection = new HubConnection(HubUrl)) { var wh = new ManualResetEventSlim(); var proxy = hubConnection.CreateHubProxy("StoreWebSocketTestHub"); proxy.On<string>("echo", m => { receivedMessages.Add(m); if (receivedMessages.Count == MessageCount) { wh.Set(); } }); await hubConnection.Start(new WebSocketTransport()); for (var i = 0; i < MessageCount; i++) { var message = "MyMessage" + i; await proxy.Invoke("Echo", message); sentMessages.Add(message); } await Task.Run(() => wh.Wait(5000)); } Assert.Equal(sentMessages, receivedMessages); }
public void ConnectToServer(string url) { this.url = url; hubConnection = new HubConnection(url); hubProxy = hubConnection.CreateHubProxy("SoftNodesHub"); bool isConnected=false; while (!isConnected) { try { hubConnection.Start().Wait(); hubConnection.Closed += OnHubConnectionClosed; hubProxy.On<Message>("ReceiveMessage", ReceiveMessage); isConnected = true; if (OnConnected != null) OnConnected(); } catch (Exception e) { if (OnConnectionFailed != null) OnConnectionFailed(e.Message); } } }
public MainWindow() { InitializeComponent(); connection = new HubConnection(@"http://iskenxan-001-site1.btempurl.com/signalr"); myHub = connection.CreateHubProxy("ChatHub"); UserNameTextBox.Focus(); }
public LiveTraceSignalRProvider(string hubUrl) { _hubConnection = new HubConnection(hubUrl); _hubConnection.Credentials = CredentialCache.DefaultCredentials; _hubProxy = _hubConnection.CreateHubProxy("LiveTraceSignalRHub"); _hubConnection.Start().Wait(); }
static void Main(string[] arguments) { var connection = new HubConnection("http://modulebuddies.azurewebsites.net/TestDraw"); // Since we are client, we must specify a URL var shapeHub = connection.CreateHubProxy("shape"); //or Kh2ndcore.CollaborativeWhiteBoard.ShapeHub // Register thge events that we are intereted in - similar to the JS client creating methods to be called back upon by the server shapeHub.On<string, int, int, int, int, string>("lineDrawn", (cid, fromX, fromY, toX, toY, color) => { Console.WriteLine("lineDrawn => Connection Id: {0}, FromX:{1}, FromY: {2}, ToX:{3}, ToY: {4}, Color: {5}", cid, fromX, fromY, toX, toY, color); }); shapeHub.On<string, int, int, string, string>("textTyped", (cid, x, y, text, color) => { Console.WriteLine("textTyped => Connection Id: {0}, x:{1}, y: {2}, text:{3}, Color: {4}", cid, x, y, text, color); }); shapeHub.On("canvasCleared", () => Console.WriteLine("Canvas Cleared!!!")); shapeHub.On<int>("connectionsCountUpdate", (c) => { Console.WriteLine("connectionsCountUpdate => Count: {0}", c); }); shapeHub.On<List<string>>("usersUpdated", (users) => { foreach (string user in users) Console.WriteLine("usersUpdated => User: {0}", user); }); // Make the connection connection.Start().Wait(); // Register the console application with a black color shapeHub.Invoke("registerUser", connection.ConnectionId, "console", "#000000").Wait(); int increment = 10; int fromXPoint = 0; int fromYPoint = 0; int toXPoint = increment; int toYPoint = 0; shapeHub.Invoke("drawLine", connection.ConnectionId, toXPoint, toYPoint, fromXPoint, fromYPoint, "#000000"); for (int i = 0; i < 10; i++) { fromYPoint += increment; toXPoint += increment; toYPoint += increment; shapeHub.Invoke("drawLine", connection.ConnectionId, toXPoint, toYPoint, fromXPoint, fromYPoint, "#000000"); Thread.Sleep(1000); } fromYPoint += (increment * 2); shapeHub.Invoke("typeText", connection.ConnectionId, fromXPoint, fromYPoint, "Hello from the console app!", "#000000"); connection.Stop(); Console.Read(); }
static void Main(string[] args) { Console.WriteLine("Client Starting..."); var hubConnection = new HubConnection("http://localhost:6666"); var hubProxy = hubConnection.CreateHubProxy("SimpleHub"); HashSet<Data> received = new HashSet<Data>(); HashSet<Data> requested = new HashSet<Data>(); object locker = new object(); hubProxy.On<Data>("Respond", s => { lock (locker) { received.Add(s); Console.WriteLine("Request: {0}\t\t Response: {1}", requested.Count, received.Count); } }); hubConnection.Start().Wait(); Console.WriteLine("Client Started"); var totalRequestsToMake = 5000; Console.WriteLine("Making {0} Requests...", totalRequestsToMake); for (int i = 0; i < totalRequestsToMake; i++) { var s = Guid.NewGuid().ToString(); requested.Add(new Data{String = s, Number = i}); } foreach (var r in requested) { if (hubConnection.State != ConnectionState.Connected) { hubConnection.Start().Wait(); } hubProxy.Invoke("Request", r) .ContinueWith(task => { if (!task.IsFaulted) return; Console.WriteLine("Error making Request: {0}", r.Number); foreach (var innerException in task.Exception.InnerExceptions) { Console.WriteLine("\t{0}", innerException); } } ); } Console.WriteLine("Requests Complete"); Console.ReadLine(); }
private async Task SetupSignalRConnection() { _connection = new HubConnection("http://pbclone.azurewebsites.net/"); _connection.StateChanged += ConnectionOnStateChanged; _mainHub = _connection.CreateHubProxy("imghub"); await _connection.Start(); _mainHub.Invoke("Create", _guid); }
public ChatHub(string url) { _connection=new HubConnection(url); _proxy = _connection.CreateHubProxy("chat"); _proxy.On("Recieve", (string message) => OnRecieved(message)); _connection.Start(); }
public MessageHubProxy() { var hubConnection = new HubConnection("http://localhost:8001/"); messageHub = hubConnection.CreateHubProxy("messageHub"); hubConnection.StateChanged += change => Console.WriteLine(change.OldState + " => " + change.NewState); messageHub.On<string>("Send", s => Console.WriteLine("Some client used send -> {0}", s)); hubConnection.Start().Wait(); }
public IHubProxy Create(string hubUrl, Action<IHubConnection> configureConnection, Action<IHubProxy> onStarted) { var connection = new HubConnection(hubUrl); if (configureConnection != null) configureConnection(connection); var proxy = connection.CreateHubProxy("EventAggregatorProxyHub"); connection.Start().ContinueWith(o => onStarted(proxy)); return proxy; }
public JabbrClient(string url) { if (String.IsNullOrWhiteSpace(url)) { throw new ArgumentNullException("url"); } Rooms = new List<string>(); Connection = new HubConnection(url); Proxy = Connection.CreateHubProxy("chat"); SubscribeToEvents(); }
private async void MainWindow_Loaded(object sender, RoutedEventArgs e) { var deviceName = ConfigurationManager.AppSettings["DeviceName"]; device = PTZDevice.GetDevice(deviceName, PTZType.Relative); url = ConfigurationManager.AppSettings["relayServerUrl"]; remoteGroup = Environment.MachineName; //They have to hardcode the group, but for us it's our machine name connection = new HubConnection(url); proxy = connection.CreateHubProxy("RelayHub"); connection.TraceLevel = TraceLevels.StateChanges | TraceLevels.Events; connection.TraceWriter = new PTZRemoteTraceWriter(Log); //Can't do this here because DirectShow has to be on the UI thread! // This would cause an obscure COM casting error with no clue what's up. So, um, ya. //proxy.On<int, int>("Move",(x,y) => device.Move(x, y)); //proxy.On<int>("Zoom", (z) => device.Zoom(z)); magic = SynchronizationContext.Current; proxy.On<int, int>("Move", (x, y) => { //Toss this over the fence from this background thread to the UI thread magic.Post((_) => { Log(String.Format("Move({0},{1})", x,y)); device.Move(x, y); }, null); }); proxy.On<int>("Zoom", (z) => { magic.Post((_) => { Log(String.Format("Zoom({0})", z)); device.Zoom(z); }, null); }); try { await connection.Start(); Log("After connection.Start()"); await proxy.Invoke("JoinRelay", remoteGroup); Log("After JoinRelay"); } catch (Exception pants) { Log(pants.GetError().ToString()); throw; } }
private async void InitializeConnection() { _connection = new HubConnection("http://localhost:44914"); _chat = _connection.CreateHubProxy("Chat"); _chat.On<string>("send", MessageReceived); SendMessageCommand = new RelayCommand( () => SendMessage(NewMessage), () => CanSendMessage()); await _connection.Start(); }
public async void RunAsync() { _hubConnection = new HubConnection(_url); _hubConnection.Received += payload => { Deployment.Current.Dispatcher.BeginInvoke(() => { OpenNotifications(payload); }); }; _hubProxy = _hubConnection.CreateHubProxy("hubs"); await _hubConnection.Start(); }
//connect to website public static void ConnectToHub() { try { con = new HubConnection("http://localhost/"); // con.TraceLevel = TraceLevels.All; // con.TraceWriter = Console.Out; proxy = con.CreateHubProxy("myHub"); // MessageBox.Show("create proxy hub called"); proxy.On <int>("SendToMachine", i => { try { } #pragma warning disable CS0168 // The variable 'ex' is declared but never used catch (Exception ex) #pragma warning restore CS0168 // The variable 'ex' is declared but never used { // Console.WriteLine(ex.Message); } }); proxy.On <string, string>("SendControl", (mac, data) => { //Console.WriteLine("server called SendControl"); //Console.WriteLine(ip + " data for IP "+data); //byte[] dataBytes = HexEncoding.GetBytes(data, out int i); try { Instructions inst = new Instructions(); byte[] ins = inst.GetValues(data); if (Machines.Any(x => x.MacAddress == mac)) { var sock = Machines.Where(x => x.MacAddress == mac).Select(x => x.workSocket).FirstOrDefault(); if (isClientConnected(sock)) { Send(sock, ins); } } } #pragma warning disable CS0168 // The variable 'ex' is declared but never used catch (Exception ex) #pragma warning restore CS0168 // The variable 'ex' is declared but never used { File.AppendAllText(docPath, Environment.NewLine + DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToShortTimeString() + "Error in SendControl to Machine : " + ex.StackTrace + " data from website " + data + " to mac: " + mac); // Console.WriteLine(ex.Message); } }); proxy.On <string>("RefreshStatus", (mac) => { byte[] data = new byte[] { 0x8B, 0xB9, 0x00, 0x03, 0x05, 0x01, 0x09 }; try { } #pragma warning disable CS0168 // The variable 'ex' is declared but never used catch (Exception ex) #pragma warning restore CS0168 // The variable 'ex' is declared but never used { // Console.WriteLine(ex.Message); } }); proxy.On <int>("CountsMachines", i => { SendCounts(); }); con.Start().ContinueWith(task => { if (task.IsFaulted) { Console.WriteLine("There was an error opening the connection with WebClient"); } //else{MessageBox.Show("Connected to signalR");} }).Wait(); } catch (Exception ex) { Console.WriteLine("not connected to WebClient " + ex.Message); con.StateChanged += Con_StateChanged; } }
public virtual async Task <bool> Connect() { if (string.IsNullOrEmpty(_endpointUri)) { throw new InvalidOperationException("WithEndpoint() must be called before you connect"); } if (string.IsNullOrEmpty(_hubName)) { throw new InvalidOperationException("WithHubName() must be called before you connect"); } if (_connection != null) { return(false); } _connection = new HubConnection(_endpointUri); _connection.StateChanged += OnConnectionStateChangedHandler; _connection.Reconnected += OnReconnectedHandler; if (_transportConnectionTimeout != null) { _connection.TransportConnectTimeout = _transportConnectionTimeout.Value; } if (_tracer != null) { _connection.TraceWriter = _tracer; _connection.TraceLevel = _traceLevel; } if (_headersProvider != null) { foreach (var header in _headersProvider()) { _connection.Headers.Add(header.Key, header.Value); } } _proxy = _connection.CreateHubProxy(_hubName); _proxySubscriber?.Invoke(_proxy); if (_connection.State != ConnectionState.Disconnected) { return(false); } try { _tracer?.WriteLine($"[{_className}] CONNECTING..."); await _connection.Start(); if (_queue != null) { await ProcessInvokeQueue(); } return(true); } catch (Exception ex) { _tracer?.WriteLine($"[{_className}] CONNECTION START ERROR: {ex.Message}"); } return(false); }
public StopwatchHubTest(Context ctx) { _connection = new HubConnection(ctx.Url); _proxy = _connection.CreateHubProxy(nameof(StopwatchHub)); }
public Client(string platform) { _platform = platform; _connection = new HubConnection("http://chrisdavetvsignalr.azurewebsites.net/"); _proxy = _connection.CreateHubProxy("ChatHub"); }
private Task Connect(HubConnection connection) { connection.StateChanged += change => _states.OnNext((ConnectionState)change.NewState); connection.Error += exception => _states.OnNext(ConnectionState.Error); var errorsProxy = connection.CreateHubProxy("relmah-errors"); //streams by error type ErrorTypes = _errors.GroupBy(e => new ErrorType(e.SourceId, e.Error.Type)); //errors errorsProxy.On <ErrorPayload>( "error", p => _errors.OnNext(p)); //sources visibility var sources = new HashSet <string>(); errorsProxy.On <IEnumerable <Source>, IEnumerable <Source> >( "sources", (es, rs) => { foreach (var e in es.Where(e => !sources.Contains(e.SourceId))) { _sources.OnNext(new SourceOperation(e, SourceOperationType.Added)); sources.Add(e.SourceId); } foreach (var r in rs.Where(e => sources.Contains(e.SourceId))) { _sources.OnNext(new SourceOperation(r, SourceOperationType.Removed)); sources.Remove(r.SourceId); } }); //recaps var groups = new Dictionary <string, IDisposable>(); errorsProxy.On <Recap>( "recap", p => { groups["*"] = ErrorTypes.Subscribe(et => { var key = et.Key.SourceId + '-' + et.Key.Type; groups.Do(key, d => d.Dispose()); var rs = from a in p.Sources where a.SourceId == et.Key.SourceId from b in a.Types where b.Name == et.Key.Type select b.Measure; var r = rs.Aggregate(0, (acc, cur) => acc + cur); groups[key] = et .Scan(0, (ka, ep) => ka + 1) .Subscribe(e => { _recaps.OnNext(new RecapAggregate(et.Key.SourceId, et.Key.Type, e + r)); }); }); }); return(connection.Start()); }
/// <summary> /// Initializes a new instance of the <see cref="T:Chat.ServiceAccess.SignalR.SignalRClient"/> class. /// </summary> public SignalRClient() { _connection = new HubConnection("http://10.0.0.128:52786/"); _proxy = _connection.CreateHubProxy("ChatHub"); }
private static void Main(string[] args) { //Set connection //string url = "http://localhost:53306//signalr"; var url = "http://ats2.rota.net.tr/signalr"; hubConnection = new HubConnection(url, "key=1"); //To enable client-side logging, set the TraceLevel and TraceWriter properties on the connection object. //Logging client events to a text file under SIGNALRCONSOLECLIENT._Console\bin\Debug var writer = new StreamWriter("clientLog.txt"); writer.AutoFlush = true; hubConnection.TraceLevel = TraceLevels.All; hubConnection.TraceWriter = writer; //Make proxy to hub based on hub name on server myHub = hubConnection.CreateHubProxy("RealDataNew"); //Start connection hubConnection.Start().ContinueWith(task => { if (task.IsFaulted) { Console.WriteLine("There was an error opening the connection:{0}", task.Exception.GetBaseException()); } else { Console.WriteLine("Connected:" + hubConnection.ConnectionId); } }).Wait(); Console.WriteLine(hubConnection.ConnectionId); myHub.On <string>("updateSettings", param => { Console.WriteLine(param); var data = JsonConvert.DeserializeObject <SettingsDto>(param); settingsDto.ContexID = data.ContexID; settingsDto.IMEI = data.IMEI; settingsDto.Period = data.Period; settingsDto.Scale = data.Scale; settingsDto.ServerIPFTP = data.ServerIPFTP; settingsDto.ServerPortFTP = data.ServerPortFTP; settingsDto.ServerUrl = data.ServerUrl; settingsDto.VehicleBrand = data.VehicleBrand; settingsDto.VehicleModel = data.VehicleModel; settingsDto.VehicleSetupState = data.VehicleSetupState; settingsDto.VehicleYear = data.VehicleYear; settingsDto.WindScreenAngle = data.WindScreenAngle; settingsDto.ZeroCoor_x = data.ZeroCoor_x; settingsDto.ZeroCoor_y = data.ZeroCoor_y; settingsDto.ZeroCoor_z = data.ZeroCoor_z; GetDeviceSettingsCall(param); }); myHub.On <string>("callDeviceSettings", param => { Console.WriteLine(param); GetDeviceSettingsCall(param); }); myHub.On <string>("callDeleteFileByName", param => { Console.WriteLine("FİLE DELETE"); GetDeviceSettingsCall(param); }); myHub.On <string>("getAllFileCallList", param => { Console.WriteLine(param); GetSendFileList(param); }); //myHub.Invoke<string>("DoSomething", "I'm doing something!!!").Wait(); #region Handle Connection Lifetime Events //Raised when the client detects a slow or frequently dropping connection. hubConnection.ConnectionSlow += () => Console.WriteLine("Connection slow"); //Raised when the connection has disconnected. hubConnection.Closed += () => Console.WriteLine("Connection stopped"); //Raised when the underlying transport has reconnected. hubConnection.Reconnected += () => Console.WriteLine("Reconnected"); //Raised when the underlying transport begins reconnecting. hubConnection.Reconnecting += () => Console.WriteLine("Reconnecting"); //Raised when the connection state changes. Provides the old state and the new state. //ConnectionState Enumeration: Connecting, Connected, Reconnecting, Disconnected hubConnection.StateChanged += (change) => Console.WriteLine("ConnectionState changed from: " + change.OldState + " to " + change.NewState); //Raised when any data is received on the connection. Provides the received data. hubConnection.Received += (data) => Console.WriteLine("Connection received" + data); #endregion Handle Connection Lifetime Events //To handle errors that SignalR raises, you can add a handler for the Error event on the connection object. hubConnection.Error += ex => Console.WriteLine("SignalR error: {0}", ex.Message); Console.Read(); hubConnection.Stop(); }
public void TestFixtureSetUp() { hubConnection = new HubConnection(TestHubSite.Url); hub = hubConnection.CreateHubProxy <ITestHub>(); hubConnection.Start().Wait(); }
/// <summary> /// Start the hub connection - populate FunctionNamesToFullNames first /// </summary> /// <returns></returns> public async Task StartAsync() { // stop any previous hub connection hubConnection?.Stop(); hubConnection?.Dispose(); // make a new hub connection hubConnection = new HubConnection(ConnectionUrl, false); hubConnection.Closed += SocketClosed; #if DEBUG //hubConnection.TraceLevel = TraceLevels.All; //hubConnection.TraceWriter = Console.Out; #endif hubProxy = hubConnection.CreateHubProxy(HubName); if (hubProxy == null) { throw new APIException("CreateHubProxy - proxy is null, this should never happen"); } // assign callbacks for events foreach (string key in FunctionNamesToFullNames.Keys) { hubProxy.On(key, async(string data) => await HandleResponse(key, data)); } // create a custom transport, the default transport is really buggy DefaultHttpClient client = new DefaultHttpClient(); customTransport = new WebsocketCustomTransport(client, ConnectInterval, KeepAlive); var autoTransport = new AutoTransport(client, new IClientTransport[] { customTransport }); hubConnection.TransportConnectTimeout = hubConnection.DeadlockErrorTimeout = TimeSpan.FromSeconds(10.0); // setup connect event customTransport.WebSocket.Connected += async(ws) => { try { SignalrSocketConnection[] socketsCopy; lock (sockets) { socketsCopy = sockets.ToArray(); } foreach (SignalrSocketConnection socket in socketsCopy) { await socket.InvokeConnected(); } } catch (Exception ex) { Logger.Info(ex.ToString()); } }; // setup disconnect event customTransport.WebSocket.Disconnected += async(ws) => { try { SignalrSocketConnection[] socketsCopy; lock (sockets) { socketsCopy = sockets.ToArray(); } foreach (SignalrSocketConnection socket in socketsCopy) { await socket.InvokeDisconnected(); } } catch (Exception ex) { Logger.Info(ex.ToString()); } try { // tear down the hub connection, we must re-create it whenever a web socket disconnects hubConnection?.Dispose(); } catch (Exception ex) { Logger.Info(ex.ToString()); } }; try { // it's possible for the hub connection to disconnect during this code if connection is crappy // so we simply catch the exception and log an info message, the disconnect/reconnect loop will // catch the close and re-initiate this whole method again await hubConnection.Start(autoTransport); // get list of listeners quickly to limit lock HubListener[] listeners; lock (this.listeners) { listeners = this.listeners.Values.ToArray(); } // re-call the end point to enable messages foreach (var listener in listeners) { foreach (object[] p in listener.Param) { await hubProxy.Invoke <bool>(listener.FunctionFullName, p); } } } catch (Exception ex) { Logger.Info(ex.ToString()); } }
static CellHub() { HubProxy = Connection.CreateHubProxy("cellHub"); }
//Конект к хабу!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! private void StartSignalR() { Debug.Log("StartSignalR"); if (HubConnection == null) { try { HubConnection = new HubConnection(signalRUrl); Debug.Log(signalRUrl); HubConnection.Error += hubConnection_Error; HubProxy = HubConnection.CreateHubProxy("h"); //подписываемся на рассылку сообщений Subscription subscriptionMessage = HubProxy.Subscribe("broadcastMessage"); subscriptionMessage.Received += subscription_DataMessage => { Debug.Log("Message1"); foreach (var item in subscription_DataMessage) { Debug.Log(item); //десериализуем объект в item ChatModel chatModel = new ChatModel(); chatModel = JsonConvert.DeserializeObject <ChatModel>(item.ToString()); //добавляем эти объекты в Pool и когда смогу, то Instantiate их в LateUpdate _chatModels = (chatModel.Name + ": " + chatModel.Message + Environment.NewLine); } }; //подписываемся на рассылку обновления игры Subscription subscription = HubProxy.Subscribe("updateGameModels"); subscription.Received += subscription_Data => { foreach (var item in subscription_Data) { //десериализуем объект syncObjectModel в item SyncObjectModel syncObjectModel = new SyncObjectModel(); syncObjectModel = JsonConvert.DeserializeObject <SyncObjectModel>(item.ToString()); //добавляем эти объекты в syncPool _syncObjectPool.Add(syncObjectModel); } }; //подписываемся на рассылку спауна Subscription subscriptionInstantiatePrefab = HubProxy.Subscribe("instantiatePrefab"); subscriptionInstantiatePrefab.Received += subscription_DataInstantiatePrefab => { if (!IsPlayerRegister) { return; } foreach (var item in subscription_DataInstantiatePrefab) { //десериализуем объект в item SyncObjectModel syncObjectModel = new SyncObjectModel(); syncObjectModel = JsonConvert.DeserializeObject <SyncObjectModel>(item.ToString()); if (syncObjectModel.Authority == HubConnection.ConnectionId) { GameHelper.CurrentPlayer = syncObjectModel; } //добавляем эти объекты в Pool и когда смогу, то Instantiate их в LateUpdate _instantiatePlayerPool.Add(syncObjectModel); } }; ////подписываемся на рассылку пуль GetComponent <SignalRShooting>().StartShooting(); //Subscription subscriptionInstantiateBullet = HubProxy.Subscribe("instantiateBullet"); //subscriptionInstantiateBullet.Received += subscription_DataInstantiateBullet => //{ // foreach (var item in subscription_DataInstantiateBullet) // { // //десериализуем объект в item // SyncObjectModel syncObjectModel = new SyncObjectModel(); // syncObjectModel = JsonConvert.DeserializeObject<SyncObjectModel>(item.ToString()); // //добавляем эти объекты в Pool и когда смогу, то Instantiate их в LateUpdate // _instantiateBulletPool.Add(syncObjectModel); // } //}; //подписываемся на рассылку выхода игрока Subscription subscriptionDisconnectPrefab = HubProxy.Subscribe("disconnectPrefab"); subscriptionDisconnectPrefab.Received += subscription_DataDisconnectPrefab => { foreach (var item in subscription_DataDisconnectPrefab) { //десериализуем объект в item SyncObjectModel disModel = new SyncObjectModel(); disModel = JsonConvert.DeserializeObject <SyncObjectModel>(item.ToString()); //добавляем эти объекты в Pool и когда смогу, то удалят их в LateUpdate _disconnectedModels.Add(disModel); } }; Debug.Log("hubConnection.Start"); HubConnection.Start(); } catch (InvalidCastException e) { Debug.Log("Ошибка: " + e); OnApplicationQuit(); } } else { Debug.Log("SignalR already connected..."); } }
public Client(string userName) { this.userName = userName; users = new Dictionary <string, DircUser>(); platform = Device.OS.ToString(); connection = new HubConnection("http://mildestve.it:1337"); hub = connection.CreateHubProxy("DircHub"); hub.On("broadcastHubMessage", (string message) => { var messageReceived = OnMessageReceived; if (messageReceived != null) { messageReceived(this, string.Format("\ud83d\udcbb {0}", message)); } }); hub.On("broadcastDircMessage", (string connectionId, string message) => { var messageReceived = OnMessageReceived; if (messageReceived != null) { var user = users[connectionId]; messageReceived(this, string.Format("{0} {1} {2}", user.UserName, DircUser.GetPlatformText(user.Platform), message)); } }); hub.On("broadcastActiveUsers", (object[] currentUsers) => { users.Clear(); foreach (var json in currentUsers) { var user = JsonConvert.DeserializeObject <DircUser>(json.ToString()); users.Add(user.ConnectionId, user); } if (!users.ContainsKey(MyConnectionId)) { users.Add(MyConnectionId, new DircUser { ConnectionId = MyConnectionId, UserName = userName, Platform = platform }); } var connectedToHub = OnConnectedToHub; if (connectedToHub != null) { connectedToHub(this, users.Values); } }); hub.On("broadcastNewUser", (string connectionId, string theUserName, string thePlatform) => { if (users.ContainsKey(connectionId)) { users[connectionId] = new DircUser { ConnectionId = connectionId, UserName = theUserName, Platform = thePlatform }; } else { users.Add(connectionId, new DircUser { ConnectionId = connectionId, UserName = theUserName, Platform = thePlatform }); } var onNewUser = OnNewUser; if (onNewUser != null) { onNewUser(this, new DircUser { ConnectionId = connectionId, UserName = theUserName, Platform = thePlatform }); } }); hub.On("broadcastUserLeft", (string connectionId) => { if (users.ContainsKey(connectionId)) { users.Remove(connectionId); } var onUserLeft = OnUserLeft; if (onUserLeft != null) { onUserLeft(this, connectionId); } }); }
public void EjecutarProceso() { String conexionMongoDb = ConfigurationManager.AppSettings["conexionMongoDb"]; //https://fm.servicesvolvobuses.com/Tmix.Cap.ExternalApi/signalr String conexionhubConnection = ConfigurationManager.AppSettings["hubConnection"]; Int32 numeroDocumentos = Int32.Parse(ConfigurationManager.AppSettings["numeroDocumentos"]); var hubConnection = new HubConnection(conexionhubConnection); MongoClient clientMongoDb = null; IMongoDatabase database = null; IMongoCollection <BsonDocument> collection = null; Boolean guardarBaseDeDatos = Boolean.TryParse(ConfigurationManager.AppSettings["guardarBaseDeDatos"].ToString(), out guardarBaseDeDatos);; Boolean ciclo = true; try { #region ClienteMongoDb clientMongoDb = new MongoClient(conexionMongoDb); database = clientMongoDb.GetDatabase("Volvo"); collection = database.GetCollection <BsonDocument>("Volvo"); DataVolvo dataVolvo = new DataVolvo(); string objDataVolvo = ""; #endregion #region ConexionVolvo object request = new { version = "1.0", vehicleEvents = new { Subscribe = true } }; string username = ConfigurationManager.AppSettings["usernamehubConnection"]; string password = ConfigurationManager.AppSettings["passwordhubConnection"]; hubConnection.Credentials = new NetworkCredential(username, password); IHubProxy stockTickerHubProxy = hubConnection.CreateHubProxy("realtimehub"); try { hubConnection.TraceLevel = TraceLevels.All; hubConnection.Start().Wait(); stockTickerHubProxy.On("OnMsgs", msg => { var listjson = JArray.Parse(msg.ToString()); foreach (var item in listjson) { JObject json = JObject.Parse(item.ToString()); List <DataVolvo> listDataVolvo = new List <DataVolvo>(); dataVolvo = new DataVolvo(); Root myDeserializedClass = JsonConvert.DeserializeObject <Root>(item.ToString()); dataVolvo.VehicleExternalId = myDeserializedClass.Message.Vehicle.ExternalId; if (myDeserializedClass.Message.Event != null) { dataVolvo.VehicleTimestamp = myDeserializedClass.Message.Event.VehicleTimestamp; } if (myDeserializedClass.Message.Position != null) { dataVolvo.Heading = myDeserializedClass.Message.Position.Heading; dataVolvo.Hdop = myDeserializedClass.Message.Position.Hdop; dataVolvo.Vdop = myDeserializedClass.Message.Position.Vdop; dataVolvo.Speed = myDeserializedClass.Message.Position.Speed; dataVolvo.Latitude = myDeserializedClass.Message.Position.Latitude; dataVolvo.Longitude = myDeserializedClass.Message.Position.Longitude; dataVolvo.Altitude = myDeserializedClass.Message.Position.Altitude; } if (myDeserializedClass.Message.Metadata != null) { if (myDeserializedClass.Message.Metadata.Signals != null) { dataVolvo.AnyDoorOpen = (myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "AnyDoorOpen").Count() == 0 ? "" : myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "AnyDoorOpen").FirstOrDefault().Value.ToString()); dataVolvo.Axle1Weight = myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "Axle1Weight").Count() == 0 ? "" : myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "Axle1Weight").FirstOrDefault().Value.ToString(); dataVolvo.Axle2Weight = myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "Axle2Weight").Count() == 0 ? "" : myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "Axle2Weight").FirstOrDefault().Value.ToString(); dataVolvo.BatteryVoltage = myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "BatteryVoltage").Count() == 0 ? "" : myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "BatteryVoltage").FirstOrDefault().Value.ToString(); dataVolvo.CurrentGear = myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "CurrentGear").Count() == 0 ? "" : myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "CurrentGear").FirstOrDefault().Value.ToString(); dataVolvo.EngineCoolantTemp = myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "EngineCoolantTemp").Count() == 0 ? "" : myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "EngineCoolantTemp").FirstOrDefault().Value.ToString(); dataVolvo.EngineOilPressure = myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "EngineOilPressure").Count() == 0 ? "" : myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "EngineOilPressure").FirstOrDefault().Value.ToString(); dataVolvo.EngineOilTemperature = myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "EngineOilTemperature").Count() == 0 ? "" : myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "EngineOilTemperature").FirstOrDefault().Value.ToString(); dataVolvo.FuelConsumption = myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "FuelConsumption").Count() == 0 ? "" : myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "FuelConsumption").FirstOrDefault().Value.ToString(); dataVolvo.FuelLevel = myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "FuelLevel").Count() == 0 ? "" : myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "FuelLevel").FirstOrDefault().Value.ToString(); dataVolvo.InsidePassengerTemperature = myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "InsidePassengerTemperature").Count() == 0 ? "" : myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "InsidePassengerTemperature").FirstOrDefault().Value.ToString(); dataVolvo.Odometer = myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "Odometer").Count() == 0 ? "" : myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "Odometer").FirstOrDefault().Value.ToString(); dataVolvo.OutsideTemperature = myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "OutsideTemperature").Count() == 0 ? "" : myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "OutsideTemperature").FirstOrDefault().Value.ToString(); dataVolvo.TotalDistance = myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "TotalDistance").Count() == 0 ? "" : myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "TotalDistance").FirstOrDefault().Value.ToString(); dataVolvo.TotalEngineHours = myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "TotalEngineHours").Count() == 0 ? "" : myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "TotalEngineHours").FirstOrDefault().Value.ToString(); dataVolvo.TotalFuelUsed = myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "TotalFuelUsed").Count() == 0 ? "" : myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "TotalFuelUsed").FirstOrDefault().Value.ToString(); } } listDataVolvo.Add(dataVolvo); objDataVolvo = JsonConvert.SerializeObject(listDataVolvo); pushDataset(objDataVolvo); BsonDocument doc = BsonDocument.Parse(json.ToString()); collection.InsertOne(doc); GC.Collect(); } }); while (true) { stockTickerHubProxy.Invoke("Subscribe", request).Wait(); } #region Anterior //hubConnection.Start().ContinueWith(task => //{ // if (task.IsFaulted) // { // Console.WriteLine("There was an error opening the connection:{0}", task.Exception.GetBaseException()); // } // else // { // while (ciclo) // { // Thread.Sleep(5000); // try // { // stockTickerHubProxy.Invoke("Subscribe", request).ContinueWith(_task => // { // if (_task.IsFaulted) // { // Console.WriteLine("There was an error calling send: {0}", _task.Exception.GetBaseException()); // } // else // { // if (_task.IsCompleted) // { // try // { // stockTickerHubProxy.On<object>("OnMsgs", msg => // { // var respuesta = msg.ToString(); // //if (guardarBaseDeDatos) // //{ // var listjson = JArray.Parse(msg.ToString()); // //foreach (var item in listjson) // //{ // JObject json = JObject.Parse(listjson[0].ToString()); // List<DataVolvo> listDataVolvo = new List<DataVolvo>(); // Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(listjson[0].ToString()); // dataVolvo.VehicleExternalId = myDeserializedClass.Message.Vehicle.ExternalId; // dataVolvo.VehicleTimestamp = myDeserializedClass.Message.Event.VehicleTimestamp; // dataVolvo.Heading = myDeserializedClass.Message.Position.Heading; // dataVolvo.Hdop = myDeserializedClass.Message.Position.Hdop; // dataVolvo.Vdop = myDeserializedClass.Message.Position.Vdop; // dataVolvo.Speed = myDeserializedClass.Message.Position.Speed; // dataVolvo.Latitude = myDeserializedClass.Message.Position.Latitude; // dataVolvo.Longitude = myDeserializedClass.Message.Position.Longitude; // dataVolvo.Altitude = myDeserializedClass.Message.Position.Altitude; // dataVolvo.AnyDoorOpen = (myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "AnyDoorOpen").Count() == 0 ? "" : myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "AnyDoorOpen").FirstOrDefault().Value.ToString()); // dataVolvo.Axle1Weight = myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "Axle1Weight").Count() == 0 ? "" : myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "Axle1Weight").FirstOrDefault().Value.ToString(); // dataVolvo.Axle2Weight = myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "Axle2Weight").Count() == 0 ? "" : myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "Axle2Weight").FirstOrDefault().Value.ToString(); // dataVolvo.BatteryVoltage = myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "BatteryVoltage").Count() == 0 ? "" : myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "BatteryVoltage").FirstOrDefault().Value.ToString(); // dataVolvo.CurrentGear = myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "CurrentGear").Count() == 0 ? "" : myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "CurrentGear").FirstOrDefault().Value.ToString(); // dataVolvo.EngineCoolantTemp = myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "EngineCoolantTemp").Count() == 0 ? "" : myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "EngineCoolantTemp").FirstOrDefault().Value.ToString(); // dataVolvo.EngineOilPressure = myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "EngineOilPressure").Count() == 0 ? "" : myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "EngineOilPressure").FirstOrDefault().Value.ToString(); // dataVolvo.EngineOilTemperature = myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "EngineOilTemperature").Count() == 0 ? "" : myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "EngineOilTemperature").FirstOrDefault().Value.ToString(); // dataVolvo.FuelConsumption = myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "FuelConsumption").Count() == 0 ? "" : myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "FuelConsumption").FirstOrDefault().Value.ToString(); // dataVolvo.FuelLevel = myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "FuelLevel").Count() == 0 ? "" : myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "FuelLevel").FirstOrDefault().Value.ToString(); // dataVolvo.InsidePassengerTemperature = myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "InsidePassengerTemperature").Count() == 0 ? "" : myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "InsidePassengerTemperature").FirstOrDefault().Value.ToString(); // dataVolvo.Odometer = myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "Odometer").Count() == 0 ? "" : myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "Odometer").FirstOrDefault().Value.ToString(); // dataVolvo.OutsideTemperature = myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "OutsideTemperature").Count() == 0 ? "" : myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "OutsideTemperature").FirstOrDefault().Value.ToString(); // dataVolvo.TotalDistance = myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "TotalDistance").Count() == 0 ? "" : myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "TotalDistance").FirstOrDefault().Value.ToString(); // dataVolvo.TotalEngineHours = myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "TotalEngineHours").Count() == 0 ? "" : myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "TotalEngineHours").FirstOrDefault().Value.ToString(); // dataVolvo.TotalFuelUsed = myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "TotalFuelUsed").Count() == 0 ? "" : myDeserializedClass.Message.Metadata.Signals.Where(x => x.Name.Trim() == "TotalFuelUsed").FirstOrDefault().Value.ToString(); // listDataVolvo.Add(dataVolvo); // objDataVolvo = JsonConvert.SerializeObject(listDataVolvo); // pushDataset(objDataVolvo); // BsonDocument doc = BsonDocument.Parse(json.ToString()); // Console.WriteLine(dataVolvo.VehicleExternalId); // //Boolean tipoInsert; // //Boolean.TryParse(ConfigurationManager.AppSettings["InsertOneAsync"].ToString(), out tipoInsert); // //if (tipoInsert) // //{ // // collection.InsertOneAsync(doc); // //} // //else // //{ // collection.InsertOne(doc); // //} // GC.Collect(); // //} // //} // }); // } // catch (Exception ec) // { // } // } // } // _task.Dispose(); // }); // task.Dispose(); // GC.Collect(); // } // catch (Exception errorInvoke) // { // Console.WriteLine("Error invoking: {0}", errorInvoke.Message); // //Envio correo // break; // } // } // } //}).Wait(); #endregion } catch (Exception ex) { hubConnection.Stop(); GC.Collect(); EjecutarProceso(); } #endregion } catch (Exception ex) { hubConnection.Stop(); GC.Collect(); EjecutarProceso(); //Envio correo } }
// 连接 server public Task ConnectAsync(string strServerUrl) { AddInfoLine("正在连接服务器 " + strServerUrl + " ..."); Connection = new HubConnection(strServerUrl); Connection.Closed += new Action(Connection_Closed); Connection.Reconnecting += Connection_Reconnecting; Connection.Reconnected += Connection_Reconnected; // Connection.Error += Connection_Error; HubProxy = Connection.CreateHubProxy("MyHub"); HubProxy.On <string, string>("AddMessage", (name, message) => OnAddMessageRecieved(name, message) ); HubProxy.On <SearchRequest>("search", (searchParam) => OnSearchBiblioRecieved(searchParam) ); HubProxy.On <string, long, long, IList <Record>, string>("responseSearch", (taskID, resultCount, start, records, errorInfo) => OnSearchResponseRecieved(taskID, resultCount, start, records, errorInfo) ); #if NO Task task = Connection.Start(); #if NO CancellationTokenSource token = new CancellationTokenSource(); if (!task.Wait(60 * 1000, token.Token)) { token.Cancel(); // labelStatusText.Text = "time out"; AddMessageLine("error", "time out"); return; } #endif while (task.IsCompleted == false) { Application.DoEvents(); Thread.Sleep(200); } if (task.IsFaulted == true) { #if NO if (task.Exception is HttpRequestException) { labelStatusText.Text = "Unable to connect to server: start server bofore connection client."; } #endif AddErrorLine(GetExceptionText(task.Exception)); return; } AddInfoLine("停止 Timer"); _timer.Stop(); //EnableControls(true); //textBox_input.Focus(); AddInfoLine("成功连接到 " + strServerUrl); this.MainForm.BeginInvoke(new Action(Login)); #endif try { return(Connection.Start() .ContinueWith((antecendent) => { if (antecendent.IsFaulted == true) { AddErrorLine(GetExceptionText(antecendent.Exception)); return; } AddInfoLine("停止 Timer"); _timer.Stop(); AddInfoLine("成功连接到 " + strServerUrl); TriggerLogin(); })); } catch (Exception ex) { AddErrorLine(ex.Message); throw ex; // return null ? } }
//connect to website public static void ConnectToHub() { try { con = new HubConnection("http://localhost:8090/"); // con.TraceLevel = TraceLevels.All; // con.TraceWriter = Console.Out; proxy = con.CreateHubProxy("myHub"); // MessageBox.Show("create proxy hub called"); proxy.On <int>("SendToMachine", i => { try { } #pragma warning disable CS0168 // The variable 'ex' is declared but never used catch (Exception ex) #pragma warning restore CS0168 // The variable 'ex' is declared but never used { // Console.WriteLine(ex.Message); } }); proxy.On <string, string>("SendControl", (mac, data) => { //Console.WriteLine("server called SendControl"); //Console.WriteLine(ip + " data for IP "+data); //byte[] dataBytes = HexEncoding.GetBytes(data, out int i); try { } #pragma warning disable CS0168 // The variable 'ex' is declared but never used catch (Exception ex) #pragma warning restore CS0168 // The variable 'ex' is declared but never used { // Console.WriteLine(ex.Message); } }); proxy.On <string>("RefreshStatus", (mac) => { byte[] data = new byte[] { 0x8B, 0xB9, 0x00, 0x03, 0x05, 0x01, 0x09 }; try { } #pragma warning disable CS0168 // The variable 'ex' is declared but never used catch (Exception ex) #pragma warning restore CS0168 // The variable 'ex' is declared but never used { // Console.WriteLine(ex.Message); } }); proxy.On <int>("Counts", i => { SendCounts(); }); con.Start().ContinueWith(task => { if (task.IsFaulted) { Console.WriteLine("There was an error opening the connection with WebClient"); } //else{MessageBox.Show("Connected to signalR");} }).Wait(); } catch (Exception ex) { Console.WriteLine("not connected to WebClient " + ex.Message); con.StateChanged += Con_StateChanged; } }
static void Main(string[] args) { Console.WriteLine("Press Enter when the server is ready..."); Console.ReadLine(); Console.Clear(); string url = "http://localhost:8080"; var hubConnection = new HubConnection(url); var hubProxy = hubConnection.CreateHubProxy("EmpireHub"); hubProxy.On("NewEmpire", x => NewEmpire(hubProxy, new Empire() { EGov = x.EGov, Empno = x.Empno, EName = x.EName })); hubProxy.On("EmpireModified", x => EmpireModified(hubProxy, (int)x)); hubProxy.On("EmpireCrushed", x => EmpireCrushed(hubProxy, x)); hubConnection.Start().ContinueWith(x => { if (x.IsFaulted) { Console.WriteLine("ERROR" + x.Exception.GetBaseException()); } else { Console.WriteLine("CONNECTED"); } }).Wait(); var task = hubProxy.Invoke <IEnumerable <string> >("GetEmpireNames"); task.Wait(); Console.WriteLine("The names of the current empires:"); foreach (var k in task.Result) { Console.WriteLine(k); } Console.WriteLine("\n"); task = hubProxy.Invoke <IEnumerable <string> >("GetGovernmentNames"); task.Wait(); Console.WriteLine("Government types:"); foreach (var k in task.Result) { Console.WriteLine(k); } Console.WriteLine("\n"); /* * nem akarom (ennél is jobban) restruktúrálni a kódot, hogy valamennyi sorrendiség még legyen azért... * egy kis delay pont elégnek tűnik, a lockkal végképp... * de lehet egy lassabb gépen (vagy éppen gyorsabb gépen?) nem elég... */ var j = new Empire() { EName = "Federation Late to the Game", EGov = "Prethoryn food", Empno = 21 }; hubProxy.Invoke("AddEmpire", j).Wait(); Task.Delay(20).Wait(); hubProxy.Invoke("ModifyEmpireGovernment", 21, "Human Federation").Wait(); Task.Delay(20).Wait(); hubProxy.Invoke("RemoveEmpire", 21).Wait(); Task.Delay(20).Wait(); lock (consoleLock) Console.WriteLine("Press Enter to stop..."); Console.ReadLine(); hubConnection.Stop(); }
public SignalRTests() { _connection = new HubConnection(TestHost.Url.ToString()); _hub = _connection.CreateHubProxy("TestHub"); _connection.Start().Wait(); }
private async void ConnectAsync() { Connection = new HubConnection(ServerURI); Connection.Closed += Connection_Closed; HubProxy = Connection.CreateHubProxy("MyHub"); //Handle incoming event from server: use Invoke to write to console from SignalR's thread HubProxy.On <string, string>("AddMessage", (name, message) => this.Invoke((Action)(() => richTextBox1.AppendText(String.Format("{0}: {1}" + Environment.NewLine, name, message)) )) ); HubProxy.On("Started", () => this.Invoke((Action)(() => richTextBox1.AppendText(String.Format("Exam Started" + Environment.NewLine)) )) ); HubProxy.On <string>("NewClient", (name) => this.Invoke((Action)(() => richTextBox1.AppendText(String.Format("Client " + name + " Connected" + Environment.NewLine)) )) ); HubProxy.On("FailedToStart", () => this.Invoke((Action)(() => richTextBox1.AppendText(String.Format("Exam Failed To Start!" + Environment.NewLine)) )) ); HubProxy.On("connected", () => this.Invoke((Action)(() => { richTextBox1.AppendText(String.Format("Connected as " + ChoosenName + "!" + Environment.NewLine)); btn_send.Enabled = true; btn_send.Text = "Send"; } )) ); HubProxy.On("rejected", () => this.Invoke((Action)(() => { richTextBox1.AppendText(String.Format("Cannot connect with name of " + ChoosenName + "!" + Environment.NewLine)); this.ChoosenName = null; btn_send.Enabled = true; btn_send.Text = "Join Chat"; } )) ); HubProxy.On <int>("TimeLeft", (timePassed) => this.Invoke((Action)(() => { TimeSpan sinavSüresi = TimeSpan.FromMinutes(30); var span = sinavSüresi.Subtract(TimeSpan.FromSeconds(timePassed)); lbl_time_left.Text = string.Format("{0}:{1}:{2}", span.Hours.ToString("0#"), span.Minutes.ToString("0#"), span.Seconds.ToString("0#")); }) )); try { await Connection.Start(); } catch (HttpRequestException) { btn_send.Enabled = false; btn_start.Enabled = false; richTextBox1.AppendText("Connected failed to " + ServerURI + Environment.NewLine); return; } richTextBox1.AppendText("Connected to server at " + ServerURI + Environment.NewLine); }
private async void GetInfo_OnGetInfoComplete(object sender, GetInformation.OnGetInfoCompletEventArgs e) { UserName = e.TxtName; BackgroundColor = e.BackgroundColor; var hubConnection = new HubConnection(urlString); var chatHubProxy = hubConnection.CreateHubProxy("ChatHub"); chatHubProxy.On<string, int, string>("UpdateChatMessage", (message, color, user) => { RunOnUiThread(() => { TextView txt = new TextView(this); txt.Text = user + ": " + message; txt.SetTextSize(Android.Util.ComplexUnitType.Sp, 20); txt.SetPadding(10, 10, 10, 10); switch (color) { case 1: txt.SetTextColor(Color.Red); break; case 2: txt.SetTextColor(Color.DarkGreen); break; case 3: txt.SetTextColor(Color.Blue); break; default: txt.SetTextColor(Color.Black); break; } txt.LayoutParameters = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent) { TopMargin = 10, BottomMargin = 10, LeftMargin = 10, RightMargin = 10, Gravity = GravityFlags.Left }; FindViewById<LinearLayout>(Resource.Id.llChatMessages) .AddView(txt); }); }); try { await hubConnection.Start(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } FindViewById<Button>(Resource.Id.btnSend).Click += async (o, e2) => { var message = FindViewById<EditText>(Resource.Id.txtChat).Text; FindViewById<EditText>(Resource.Id.txtChat).Text = null; await chatHubProxy.Invoke("SendMessage", new object[] { message, BackgroundColor, UserName }); }; }
private async void InitializeSignalR(string url) { if (_hubConnection != null) { _hubConnection.Stop(); } _hubConnection = new HubConnection(url); _soulstoneHub = _hubConnection.CreateHubProxy("soulstoneHub"); _soulstoneHub.On <int, int, int>("PlaySong", (hostId, playlistId, songId) => { try { if (hostId == HostId) { var entities = new SoulstoneEntities(); var song = entities.Songs.Find(songId); SetPlayerStatusInfo(song); _playerStatus.PlaylistId = playlistId; _playerStatus.IsPlaying = true; if (song != null) { PlayFile(song.FileName); LookForNextSong(); } } } catch (Exception ex) { IocUnityContainer.Instance.Resolve <ILogManager>().DefaultLogger.Error.Write(ex.Message, ex); ConsoleLog("An error has occurred: " + ex.Message); } }); _soulstoneHub.On <int>("Play", hostId => { try { if (hostId == HostId) { ConsoleLog("Play"); Player.Dispatcher.BeginInvoke(new Action(() => Player.Play())); _playerStatus.IsPlaying = true; _soulstoneHub.Invoke("PlayerStatus", HostId, _playerStatus); } } catch (Exception ex) { IocUnityContainer.Instance.Resolve <ILogManager>().DefaultLogger.Error.Write(ex.Message, ex); ConsoleLog("An error has occurred: " + ex.Message); } }); _soulstoneHub.On <int>("Stop", hostId => { try { if (hostId == HostId) { Player.Dispatcher.BeginInvoke(new Action(() => Player.Stop())); ConsoleLog("Stop"); _playerStatus.IsPlaying = false; _soulstoneHub.Invoke("PlayerStatus", HostId, _playerStatus); } } catch (Exception ex) { IocUnityContainer.Instance.Resolve <ILogManager>().DefaultLogger.Error.Write(ex.Message, ex); ConsoleLog("An error has occurred: " + ex.Message); } }); _soulstoneHub.On <int>("Pause", hostId => { try { if (hostId == HostId) { Player.Dispatcher.BeginInvoke(new Action(() => Player.Pause())); _playerStatus.IsPlaying = false; ConsoleLog("Pause"); _soulstoneHub.Invoke("PlayerStatus", HostId, _playerStatus); } } catch (Exception ex) { IocUnityContainer.Instance.Resolve <ILogManager>().DefaultLogger.Error.Write(ex.Message, ex); ConsoleLog("An error has occurred: " + ex.Message); } }); _soulstoneHub.On <int, int>("Volume", (hostId, volumeValue) => { try { if (hostId == HostId) { Player.Dispatcher.BeginInvoke(new Action(() => { UpdateVolume(volumeValue * 0.1); })); } } catch (Exception ex) { IocUnityContainer.Instance.Resolve <ILogManager>().DefaultLogger.Error.Write(ex.Message, ex); ConsoleLog("An error has occurred: " + ex.Message); } }); _soulstoneHub.On <int>("Mute", hostId => { try { if (hostId == HostId) { Player.Dispatcher.BeginInvoke(new Action(() => { ToogleMute(); })); } } catch (Exception ex) { IocUnityContainer.Instance.Resolve <ILogManager>().DefaultLogger.Error.Write(ex.Message, ex); ConsoleLog("An error has occurred: " + ex.Message); } }); _soulstoneHub.On <int>("GetPlayerStatus", hostId => { try { if (hostId == HostId) { _soulstoneHub.Invoke("PlayerStatus", hostId, _playerStatus); } } catch (Exception ex) { IocUnityContainer.Instance.Resolve <ILogManager>().DefaultLogger.Error.Write(ex.Message, ex); ConsoleLog("An error has occurred: " + ex.Message); } }); _soulstoneHub.On <int>("Shuffle", hostId => { try { if (hostId == HostId) { Player.Dispatcher.BeginInvoke(new Action(() => { _playerStatus.IsShuffleEnabled = !_playerStatus.IsShuffleEnabled; ConsoleLog(string.Format("Shuffle:{0}", _playerStatus.IsShuffleEnabled)); LookForNextSong(); })); } } catch (Exception ex) { IocUnityContainer.Instance.Resolve <ILogManager>().DefaultLogger.Error.Write(ex.Message, ex); ConsoleLog("An error has occurred: " + ex.Message); } }); _soulstoneHub.On <int>("NextSong", hostId => { try { if (hostId == HostId) { Player.Dispatcher.BeginInvoke(new Action(() => { PlayNextFile(); LookForNextSong(); })); } } catch (Exception ex) { IocUnityContainer.Instance.Resolve <ILogManager>().DefaultLogger.Error.Write(ex.Message, ex); ConsoleLog("An error has occurred: " + ex.Message); } }); try { await _hubConnection.Start(); } catch { ConsoleLog("SignalR connection could not be established"); throw; } ConsoleLog("SignalR connection established"); }
static void Main() { //Set connection var connection = new HubConnection("http://localhost:57422/"); //Make proxy to hub based on hub name on server var myHub = connection.CreateHubProxy("DashHub"); //Start connection 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(); var rand = new Random(); var i = 0; while (true) { var deviceData = DeviceDataStorms[rand.Next(0, DeviceDataStorms.Length)]; deviceData.Timestamp = DateTime.Now.ToString("O"); var json = JsonConvert.SerializeObject(deviceData, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }); myHub.Invoke <string>("Send", json).ContinueWith(task => { if (task.IsFaulted) { Console.WriteLine("There was an error calling send: {0}", task.Exception.GetBaseException()); } else { } }); var alertData = AlertMessage[rand.Next(0, AlertMessage.Length)]; var jsonAlert = JsonConvert.SerializeObject(alertData, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }); myHub.Invoke <string>("Alert", jsonAlert).ContinueWith(task => { if (task.IsFaulted) { Console.WriteLine("There was an error calling send: {0}", task.Exception.GetBaseException()); } else { } }); i++; Thread.Sleep(1000); if (i > 10) { var averageData = AverageDataStorms[rand.Next(0, AverageDataStorms.Length)]; averageData.Timestamp = DateTime.Now.ToString("O"); var jsonAvg = JsonConvert.SerializeObject(averageData, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }); myHub.Invoke <string>("Average", jsonAvg).ContinueWith(task => { if (task.IsFaulted) { Console.WriteLine("There was an error calling send: {0}", task.Exception.GetBaseException()); } else { } }); i = 0; } } Console.Read(); connection.Stop(); }
static async Task Test(string hostname, string username, string password) { var httpClient = CreateHttpClient(hostname, username, password); string url = "/hpc/jobs/jobFile"; string xmlJob = @" <Job Name=""SimpleJob""> <Tasks> <Task CommandLine=""echo Hello"" MinCores=""1"" MaxCores=""1"" /> </Tasks> </Job> "; Console.WriteLine($"Create a job from XML:\n{xmlJob}"); var response = await httpClient.PostAsync(url, new StringContent(JsonConvert.SerializeObject(xmlJob), Encoding.UTF8, "application/json")); await CheckHttpErrorAsync(response); string result = await response.Content.ReadAsStringAsync(); var jobId = int.Parse(result); url = $"{httpClient.BaseAddress}/hpc"; var hubConnection = new HubConnection(url); // { TraceLevel = TraceLevels.All, TraceWriter = Console.Error }; hubConnection.Headers.Add("Authorization", BasicAuthHeader(username, password)); hubConnection.Error += ex => Console.WriteLine($"HubConnection Exception:\n{ex}"); var jobEventHubProxy = hubConnection.CreateHubProxy("JobEventHub"); string prevJobState = "Configuring"; jobEventHubProxy.On("JobStateChange", (int id, string state, string previousState) => { Console.WriteLine($"Job: {id}, State: {state}, Previous State: {previousState}"); Assert(id == jobId); Assert(string.Equals(previousState, prevJobState, StringComparison.OrdinalIgnoreCase)); prevJobState = state; }); var taskEventHubProxy = hubConnection.CreateHubProxy("TaskEventHub"); string prevTaskState = "Submitted"; taskEventHubProxy.On("TaskStateChange", (int id, int taskId, int instanceId, string state, string previousState) => { Console.WriteLine($"Job: {id}, Task: {taskId}, State: {state}, Previous State: {previousState}"); Assert(id == jobId); Assert(string.Equals(previousState, prevTaskState, StringComparison.OrdinalIgnoreCase)); prevTaskState = state; }); Console.WriteLine($"Connecting to {url} ..."); try { await hubConnection.Start(new WebSocketTransport()); } catch (Exception ex) { throw new Exception($"Exception on starting:\n{ex}"); } Console.WriteLine($"Begin to listen..."); try { await jobEventHubProxy.Invoke("BeginListen", jobId); await taskEventHubProxy.Invoke("BeginListen", jobId); } catch (Exception ex) { throw new Exception($"Exception on invoking server method:\n{ex}"); } Console.WriteLine($"Submit job {jobId}"); url = $"/hpc/jobs/{jobId}/submit"; response = await httpClient.PostAsync(url, new StringContent("")); await CheckHttpErrorAsync(response); await Task.Delay(30 * 1000); Assert(string.Equals(prevJobState, "Finished", StringComparison.OrdinalIgnoreCase)); Assert(string.Equals(prevTaskState, "Finished", StringComparison.OrdinalIgnoreCase)); }
public IHubProxyWrapper CreateHubProxy(string hubName) { return(new HubProxyWrapperOld(_wrapped.CreateHubProxy(hubName))); }
public override void Login(string Username, string Password, string twofa) { HttpWebRequest getHeaders = HttpWebRequest.Create("https://betking.io/bitcoindice#dice") as HttpWebRequest; if (Prox != null) { getHeaders.Proxy = Prox; } var cookies = new CookieContainer(); getHeaders.CookieContainer = cookies; HttpWebResponse Response = null; string rqtoken = ""; string s1 = ""; try { Response = (HttpWebResponse)getHeaders.GetResponse(); s1 = new StreamReader(Response.GetResponseStream()).ReadToEnd(); string tmp = s1.Substring(s1.IndexOf("__RequestVerificationToken") + "__RequestVerificationToken\" type=\"hidden\" value=\"".Length); s = rqtoken = tmp.Substring(0, tmp.IndexOf("\"")); } catch (WebException e) { finishedlogin(false); return; } getHeaders = HttpWebRequest.Create("https://betking.io/account/login") as HttpWebRequest; if (Prox != null) { getHeaders.Proxy = Prox; } getHeaders.CookieContainer = new CookieContainer(); foreach (Cookie c in Response.Cookies) { getHeaders.CookieContainer.Add(c); } getHeaders.Method = "POST"; string post = string.Format("userName={0}&password={1}&twoFactorCode={2}&__RequestVerificationToken={3}", Username, Password, twofa, rqtoken); getHeaders.ContentType = "application/x-www-form-urlencoded"; getHeaders.ContentLength = post.Length; using (var writer = new StreamWriter(getHeaders.GetRequestStream())) { string writestring = post as string; writer.Write(writestring); } try { Response = (HttpWebResponse)getHeaders.GetResponse(); s1 = new StreamReader(Response.GetResponseStream()).ReadToEnd(); if (!s1.ToLower().Contains("true")) { finishedlogin(false); return; } /*string tmp = s1.Substring(s1.IndexOf("__RequestVerificationToken") + "__RequestVerificationToken\" type=\"hidden\" value=\"".Length); * rqtoken = tmp.Substring(0, tmp.IndexOf("\""));*/ } catch (WebException e) { Response = (HttpWebResponse)e.Response; s1 = new StreamReader(Response.GetResponseStream()).ReadToEnd(); finishedlogin(false); return; } foreach (Cookie c in Response.Cookies) { if (c.Name == "__RequestVerificationToken") { rqtoken = c.Value; } Cookies.Add(c); } Cookies.Add((new Cookie("PRC_Affiliate", "357", "/", "betking.io"))); con.CookieContainer = Cookies; try { getHeaders = HttpWebRequest.Create("https://betking.io/bitcoindice#dice") as HttpWebRequest; if (Prox != null) { getHeaders.Proxy = Prox; } getHeaders.CookieContainer = Cookies; Response = (HttpWebResponse)getHeaders.GetResponse(); string stmp = new StreamReader(Response.GetResponseStream()).ReadToEnd(); string sstmp = stmp.Substring(stmp.IndexOf("__RequestVerificationToken") + "__RequestVerificationToken\" type=\"hidden\" value=\"".Length); s = rqtoken = sstmp.Substring(0, sstmp.IndexOf("\"")); dicehub = con.CreateHubProxy("diceHub"); con.Start().Wait(); dicehub.Invoke("joinChatRoom", 1); dicehub.On <string, string, string, int, int, bool>("chat", ReceivedChat); dicehub.On <string, string, string, int, bool>("receivePrivateMesssage", ReceivedChat); dicehub.On <PRCMYstats>("diceBetResult", DiceBetResult); dicehub.On <PRCResetSeed>("generateServerSeedResult", GenerateServerSeedResult); dicehub.On <PRCResetSeed>("saveClientSeedResult", SaveClientSeedResult); getHeaders = HttpWebRequest.Create("https://betking.io/account/GetUserAccount") as HttpWebRequest; if (Prox != null) { getHeaders.Proxy = Prox; } getHeaders.CookieContainer = Cookies; Response = (HttpWebResponse)getHeaders.GetResponse(); s1 = new StreamReader(Response.GetResponseStream()).ReadToEnd(); PRCUser tmp = json.JsonDeserialize <PRCUser>(s1); balance = (decimal)tmp.AvailableBalance; profit = (decimal)tmp.Profit; wagered = (decimal)tmp.Wagered; bets = (int)tmp.NumBets; wins = (int)tmp.Wins; losses = (int)tmp.Losses; UserID = tmp.Id; Parent.updateBalance((decimal)(balance)); Parent.updateBets(tmp.NumBets); Parent.updateLosses(tmp.Losses); Parent.updateProfit(profit); Parent.updateWagered(wagered); Parent.updateWins(tmp.Wins); //Parent.updateDeposit(tmp.DepositAddress); getHeaders = HttpWebRequest.Create("https://betking.io/account/GetCurrentSeed?gameType=0") as HttpWebRequest; if (Prox != null) { getHeaders.Proxy = Prox; } getHeaders.CookieContainer = Cookies; Response = (HttpWebResponse)getHeaders.GetResponse(); s1 = new StreamReader(Response.GetResponseStream()).ReadToEnd(); prcSeed getseed = json.JsonDeserialize <prcSeed>(s1); client = getseed.ClientSeed; serverhash = getseed.ServerHash; try { getHeaders = HttpWebRequest.Create("https://betking.io/account/getDepositAddress") as HttpWebRequest; if (Prox != null) { getHeaders.Proxy = Prox; } getHeaders.CookieContainer = Cookies; Response = (HttpWebResponse)getHeaders.GetResponse(); s1 = new StreamReader(Response.GetResponseStream()).ReadToEnd(); PRCDepost dep = json.JsonDeserialize <PRCDepost>(s1); Parent.updateDeposit(dep.Address); } catch { new System.Threading.Thread(GetDeposit).Start(); } finishedlogin(true); return; } catch { finishedlogin(false); return; } finishedlogin(false); }
public ClientHub(string url, string hub) { this.hubConnection = new HubConnection(url); this.hubProxy = hubConnection.CreateHubProxy(hub); this.startConnecionHub(); }
public async Task FarmGroupAddCompletesSuccessfully(TransportType transportType) { // https://github.com/SignalR/SignalR/issues/3337 // Each node shares the same bus but are independent servers const int nodeCount = 2; var counters = new Infrastructure.PerformanceCounterManager(); var configurationManager = new DefaultConfigurationManager(); // Ensure /send and /connect requests get handled by different servers Func <string, int> scheduler = url => url.Contains("/send") ? 0 : 1; using (EnableDisposableTracing()) using (var bus = new MessageBus(new StringMinifier(), new TraceManager(), counters, configurationManager, 5000)) using (var loadBalancer = new LoadBalancer(nodeCount, scheduler)) { loadBalancer.Configure(app => { var resolver = new DefaultDependencyResolver(); resolver.Register(typeof(IMessageBus), () => bus); app.MapSignalR(new HubConfiguration { Resolver = resolver }); }); using (var connection = new HubConnection("http://goo/")) { var proxy = connection.CreateHubProxy("FarmGroupHub"); const string group = "group"; const string message = "message"; var mre = new AsyncManualResetEvent(); proxy.On <string>("message", m => { if (m == message) { mre.Set(); } }); Client.Transports.IClientTransport transport; switch (transportType) { case TransportType.LongPolling: transport = new Client.Transports.LongPollingTransport(loadBalancer); break; case TransportType.ServerSentEvents: transport = new Client.Transports.ServerSentEventsTransport(loadBalancer); break; default: throw new ArgumentException("transportType"); } await connection.Start(transport); await proxy.Invoke("JoinGroup", group); await proxy.Invoke("SendToGroup", group, message); Assert.True(await mre.WaitAsync(TimeSpan.FromSeconds(5))); } } }
private void Start() { Instance = this; dozwoloneRuchy = new bool[8, 8]; poczatekGry(); var connection = new HubConnection(String.Concat("http://", MenuManager.ip1, ":", MenuManager.port1, "/")); myHub = connection.CreateHubProxy("MyHub"); connection.Start().Wait(); myHub.On <Guid, int[]>("addMessage", (s1, message) => { if (message[0] == -1) { queue.Add(new Task(() => { Debug.Log("MAT"); GameObject go = Instantiate(matokno) as GameObject; go.SetActive(true); //queue.Clear(); })); } else if (message[0] == -2) { queue.Add(new Task(() => { Debug.Log("PAT"); // throw new Exception("pat"); GameObject go = Instantiate(patokno) as GameObject; go.SetActive(true); //queue.Clear(); })); } else if (s1 != playerName && message[0] >= 0) { queue.Add(new Task(() => { wybranaBierka = Bierki[message[0], message[1]]; wybraneX = message[0]; wybraneY = message[1]; dozwoloneRuchy[message[2], message[3]] = true; Roszada(message[2], message[3]); RuchBierka(message[2], message[3]); mojRuch = true; })); } else if (message[0] == -3 && s1 != playerName) { queue.Add(new Task(() => { BierkiwGrze.Remove(Bierki[message[2], message[3]].gameObject); Destroy(Bierki[message[2], message[3]].gameObject); BierkaSpawn(message[1], message[2], message[3], -90f, 0); if (sprawdzSzachCalosc()) { szachujacaBierka = Bierki[message[2], message[3]]; } })); } }); }
public ChatServices() { _connection = new HubConnection("http://xamarin-chat.azurewebsites.net/"); _proxy = _connection.CreateHubProxy("ChatHub"); }
public async Task <ActionResult> GenerateAnswer(ChatViewModel model) { // Iteracción entre el usuario y s@mi Bot // Variables tipo texto string textUser = model.Message, queryLuis = "", respuestaFinal = "", intencion = "", respuestaSami = "", entidad = "", casoJson = "", respuestaLuis = "" , puntajeLuis = "", puntajeQnA = "", respuesta = ""; // Variables tipo texto array string[] returnLuisFormat = null; // Variables tipo enteros int operacionMatematica = 0; // Instancia con las APIS var bot = new ConnectToBot(); var uri = new Uri(Request.Url.AbsoluteUri); List <string> exchangeRate = new List <string>(); //Generate a URL from the URI var url = $"{uri.Scheme}://{uri.Host}:{uri.Port}"; //Generate a hub client to specified url var hub = new HubConnection(url); //Generate a hub proxy to specified hub IHubProxy proxy = hub.CreateHubProxy("SamiChatHub"); var datosSamiApi = (from samiapi in db.ApiConversacions select samiapi).First(); var resultadosApi = await bot.GetAnswersAsync(datosSamiApi.SamiApiKey , datosSamiApi.SamiApiLink , textUser , model.CompanyId , model.IdUserAspNetUser , model.OS , model.Name); model.RepliedByBot = true; casoJson = resultadosApi.TipoCaso; respuesta = resultadosApi.Respuesta; respuestaLuis = resultadosApi.FormatoLuis; intencion = resultadosApi.Intencion; entidad = resultadosApi.Entidades; puntajeLuis = resultadosApi.PuntajeLuis; puntajeQnA = resultadosApi.PuntajeQnA; /* * Aquí pasa la función para guardar a la tabla de reporte. */ if (casoJson != "2" && casoJson != "5" && casoJson != null) { string[] convertido = respuestaSami.Split(new[] { "<script>" }, StringSplitOptions.None); var chatReportSami = SaveReportChatSami(model.IdSesionSaved, model.Name, model.IdUserAspNetUser, textUser, respuesta, respuestaLuis, model.OS, intencion, entidad, puntajeLuis, puntajeQnA, "Web"); } switch (casoJson) { case "1": // Escenario sin paso de QnA: ¿Que necesitas de....?, ¿Qué necesitas ...? respuestaFinal = respuesta + "<script>nextQuery();</script>"; rating = null; break; case "2": var consultaCa = new ConsultaCA(); // Aquí se guarda la petición en consultar un ticket o caso. string numericPhone = new string(textUser.ToCharArray().Where(c => Char.IsDigit(c)).ToArray()); // Pasa por el método para conectarse con CA y consulta el ticket solicitado. respuestaFinal = await consultaCa.GetTicketCa(numericPhone, model.CompanyId) + "<script>nextQuery();</script>"; break; case "3": //Escenario respuesta de QnA sin FeedBack respuestaFinal = respuesta + "<script>nextQuery();</script>"; // Se desactiva el panel de calificación. rating = null; break; case "4": //Escenario de QnA con FeedBack respuestaFinal = respuesta; // Activa el panel de calificación rating = ReturnView(); break; case "5": // Escenario pasa al agente automático. respuestaFinal = "No tengo una respuesta a tu pregunta en este momento.<script>AutoQueueForAgentChat();</script>"; rating = null; break; case "6": // Escenario pasa al agente automático. respuestaFinal = respuesta + "<script>AutoQueueForAgentChat();</script>"; rating = null; break; default: // Escenario pasa al agente automático. respuestaFinal = "No estoy entrenado para ese tipo de preguntas. ¿En qué te puedo ayudar? <script>nextQuery();</script>"; rating = null; break; } //Start hub connection await hub.Start(); //Set chat model values model.Name = "Pólux"; model.Message = respuestaFinal; model.ProfilePictureLocation = "bot-avatar.png"; //Send answer message await proxy.Invoke <ChatViewModel>("sendChatMessage", model); //Send acceptable answer or switch to agent prompt if (rating != null) { // Tiempo de espera por longitud. operacionMatematica = respuestaFinal.Length * 50; Thread.Sleep(operacionMatematica); model.Message = rating; await proxy.Invoke <ChatViewModel>("sendChatMessage", model); } //Stop hub connection hub.Stop(); return(View(model)); }
public SignalRClient() { _connection = new HubConnection("http://192.168.0.6/BabyRegisterWeb"); _proxy = _connection.CreateHubProxy("BabyRegisterHub"); }