Beispiel #1
4
        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");
        }
Beispiel #2
0
        private async Task OpenConnection()
        {
            var url = $"http://{await _serverFinder.GetServerAddressAsync()}/";

            try
            {
                _hubConnection = new HubConnection(url);

                _hubProxy = _hubConnection.CreateHubProxy("device");
                _hubProxy.On<string>("hello", message => Hello(message));
                _hubProxy.On("helloMsg", () => Hello("EMPTY"));
                _hubProxy.On<long, bool, bool>("binaryDeviceUpdated", (deviceId, success, binarySetting) => InvokeDeviceUpdated(deviceId, success, binarySetting: binarySetting));
                _hubProxy.On<long, bool, double>("continousDeviceUpdated", (deviceId, success, continousSetting) => InvokeDeviceUpdated(deviceId, success, continousSetting));

                await _hubConnection.Start();

                await _hubProxy.Invoke("helloMsg", "mobile device here");

                Debug.WriteLine($"{nameof(RealTimeService)}.{nameof(OpenConnection)} SignalR connection opened");
            }
            catch (Exception e)
            {
                Debug.WriteLine($"{nameof(RealTimeService)}.{nameof(OpenConnection)} ex: {e.GetType()}, msg: {e.Message}");
            }
        }
Beispiel #3
0
        private async Task RunDemo(string url)
        {
            cde = new CountdownEvent(invocations);
            ITaskAgent client = this;
            ITaskScheduler server = this;

            var hubConnection = new HubConnection(url);
            hubConnection.TraceWriter = _traceWriter;

            _hubProxy = hubConnection.CreateHubProxy("TaskSchedulerHub");            
            _hubProxy.On<TimeSpan>("RunSync", client.RunSync);
            _hubProxy.On<TimeSpan>("RunAsync", (data) => client.RunAsync(data));

            await hubConnection.Start(new LongPollingTransport());

            var smallDuration = TimeSpan.FromMilliseconds(500);
            var largeDuration = TimeSpan.FromSeconds(10);

            for (int i = 0; i < invocations; i++ )
            {
                server.AssignMeShortRunningTask(smallDuration);
                server.AssignMeLongRunningTask(largeDuration);
            }

            cde.Wait();
        }
Beispiel #4
0
Datei: Hub.cs Projekt: lx223/Q3
        public Hub(User user, Dispatcher dispatcher)
        {
            this.user = user;
            this.dispatcher = dispatcher;

#if DEBUG && !LIVE
            hubConnection = new HubConnection("http://localhost:51443/");
#else
            hubConnection = new HubConnection("http://poolq3.zoo.lan/"); 
#endif

            hubConnection.TraceLevel = TraceLevels.All;
            hubConnection.TraceWriter = new NLogTextWriter("signalr");

            hub = hubConnection.CreateHubProxy("QHub");
            hub.On<Queue>("NewQueue", q => RaiseEvent("created", QueueCreated, q));
            hub.On<Queue>("QueueMembershipChanged", q => RaiseEvent("membershipchanged", QueueMembershipChanged, q));
            hub.On<Queue>("QueueStatusChanged", q => RaiseEvent("statuschanged", QueueStatusChanged, q));
            hub.On<int, User, string>("QueueMessageSent", RaiseMessageEvent);
            hub.On<int>("NagQueue", id => RaiseEvent("nag", QueueNagged, id));
            hubConnection.Headers["User"] = this.user.ToString();
            hubConnection.StateChanged += HubConnectionOnStateChanged;
            hubConnection.Error += e => logger.Error(e, "hub error");

            TryConnect();
        }
 public async Task SetHub(IHubProxy hub)
 {
     this.hub = hub;
     hub.On<string>("info", info => ServedInformation = string.Join("\r\n", ServedInformation, info));
     hub.On("completed", () => _isCompleted = true);
     await hub.Invoke("SetupServer");
 }
        public ShellViewModel()
        {
            _hubConnection = new HubConnection("http://localhost:52029/");
            _gameHub = _hubConnection.CreateHubProxy("ScattergoramentHub");

            _gameHub.On<char, DateTime>("gameStart", GameStart);
            _gameHub.On<string, DateTime>("gameEnd", GameEnd);
            _gameHub.On<bool, char, DateTime>("gameStatus", GameStatus);

            _timer = new DispatcherTimer();
            _timer.Interval = TimeSpan.FromMilliseconds(100);
            _timer.Tick += _timer_Tick;
            _timer.Start();

            _hubConnection.Start()
                .ContinueWith(task=>
                    {
                        if (task.IsFaulted)
                        {
                            Console.WriteLine("An error occurred during the method call {0}", task.Exception.GetBaseException());
                        }
                        else
                        {
                            RegisterPlayer();
                        }
                    }
                    );
        }
Beispiel #7
0
        public void HubInitial()
        {
            Connection = new HubConnection("http://54.69.68.144:8733/signalr");

            HubProxy = Connection.CreateHubProxy("ChatHub");

            HubProxy.On<string>("AddMessage",(msg) =>
                Device.BeginInvokeOnMainThread(() =>
                {
                   MessageService.AddMessage(msg,false,_controls);
                }));

            HubProxy.On<int>("GetNumberOfUsers", (count) =>
                Device.BeginInvokeOnMainThread(() =>
                {
                    MessageService.SetUsersCount(count, _controls);
                }));

            try
            {
                Connection.Start().Wait();
                Device.BeginInvokeOnMainThread(() =>
                {
                    _controls.ProgressBar.ProgressTo(.9, 250, Easing.Linear);
                });
            }
            catch (Exception e)
            {
                MessageTemplate.RenderError("Невозможно подключиться к серверу");
            }
            HubProxy.Invoke("GetNumberOfUsers");
        }
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();
        }
Beispiel #9
0
        public Chat(HubConnection connection)
        {
            _chat = connection.CreateHubProxy("Chat");

            _chat.On<User>("markOnline", user =>
            {
                if (UserOnline != null)
                {
                    UserOnline(user);
                }
            });

            _chat.On<User>("markOffline", user =>
            {
                if (UserOffline != null)
                {
                    UserOffline(user);
                }
            });

            _chat.On<Message>("addMessage", message =>
            {
                if (Message != null)
                {
                    Message(message);
                }
            });
        }
Beispiel #10
0
 public void Start()
 {
     _connection = new HubConnection("http://localhost:27367/");
     _job=_connection.CreateHubProxy("JobStatusHub");
     _job.On("started",onStarted);
     _job.On("finished", onFinished);
     _connection.Start();
 }
Beispiel #11
0
 public void Start()
 {
     _connection = new HubConnection(_testswarmUrl);
     _job = _connection.CreateHubProxy("JobStatusHub");
     _job.On("started", onStarted);
     _job.On("finished", onFinished);
     _connection.Start();
 }
        private void RegisterEventHandlers(IHubProxy proxy)
        {
            // Register event for setting the QR-code for client URL
            proxy.On<Uri>("SetQrCode", SetQrCode);

            // Register events for controlling the robot
            proxy.On<string>("LockRobot", LockRobot);
            proxy.On<string>("UnlockRobot", UnlockRobot);
        }
Beispiel #13
0
 public async Task StartAsync()
 {
     hubConnection = new HubConnection(Url);
     eventHubProxy = hubConnection.CreateHubProxy("EventHub");
     eventHubProxy.On<Message>("Receive",
         async message => await FilterMessage(message, async () => await OnReceive(message)));
     eventHubProxy.On<Message>("UpdateConfiguration",
         async message => await FilterMessage(message, async () => await OnUpdateConfiguration(message.Values["Locations"] as IEnumerable<Location>)));
     await hubConnection.Start();
     await eventHubProxy.Invoke<Message>("RequestConfiguration");
 }
Beispiel #14
0
        public SignalRClient(IEventAggregator eventAggregator, IApplicationSettings settings)
        {
            this.eventAggregator = eventAggregator;

            connection = new HubConnection(settings.Endpoint);
            hubProxy = connection.CreateHubProxy(HubName);

            hubProxy.On<string>(ProductUpdatedEvent.HubEventName, OnProductUpdatedRemote);
            hubProxy.On<List<string>>(ProductUpdatedBatchEvent.HubEventName, OnProductUpdatedBatchRemote);
            hubProxy.On<List<string>>(ProductDeletedBatchEvent.HubEventName, OnProductDeletedBatchRemote);
        }
Beispiel #15
0
        public SignalRClient(IEventAggregator eventAggregator)
        {
            this.eventAggregator = eventAggregator;

            connection = new HubConnection(System.Windows.Browser.HtmlPage.Document.DocumentUri.ToString());
            hubProxy = connection.CreateHubProxy(HubName);

            hubProxy.On<string>(ProductUpdatedEvent.HubEventName, OnProductUpdatedRemote);
            hubProxy.On<List<string>>(ProductUpdatedBatchEvent.HubEventName, OnProductUpdatedBatchRemote);
            hubProxy.On<List<string>>(ProductDeletedBatchEvent.HubEventName, OnProductDeletedBatchRemote);
        }
Beispiel #16
0
		public virtual void ConnectToServer() {
			hubConnection = new HubConnection("http://localhost:52807/signalR", false);
			hubProxy = hubConnection.CreateHubProxy("QmsHub");

			hubProxy.On("OnRegisterConfirm", OnRegisteConfirm);
			hubProxy.On<Guid>("AddPersonToQueue", AddPersonToQueue);
			hubProxy.On("OnStart", OnStart);
			hubProxy.On("OnStop", OnStop);

			hubConnection.Start().Wait();
			OnConnectedToServer();
		}
        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;
            }
        }
        public bool Connect(Gateway gateway, string serverUrl, string connectionPassword)
        {
            DebugState(String.Format("Connecting to server {0}... ", serverUrl));

            isAuthorized = false;

            var querystringData = new Dictionary<string, string>();
            querystringData.Add("IsGateway", "true");
            querystringData.Add("ConnectionPassword", connectionPassword);

            hubConnection = new HubConnection(serverUrl, querystringData);
            hubProxy = hubConnection.CreateHubProxy("gatewayHub");

            try
            {
                hubProxy.On<string>("clearLog", ClearLog);
                hubProxy.On("clearNodes", ClearNodes);
                hubProxy.On<string>("getLog", GetLog);
                hubProxy.On<string>("getNodes", GetNodes);
                hubProxy.On<string>("getGatewayInfo", GetGatewayInfo);
                hubProxy.On<string>("getGatewayHardwareConnected", GetGatewayHardwareConnected);
                hubProxy.On("authorizationFailed", AuthorizationFailed);
                hubProxy.On("authorizationCompleted", AuthorizationCompleted);
                hubProxy.On<string, string>("sendMessage", SendMessage);

                hubConnection.Start().Wait();
                hubConnection.Closed += Disconnect;

                this.gateway = gateway;
                gateway.OnMessageRecievedEvent += OnMessageRecievedEvent;
                gateway.OnMessageSendEvent += OnMessageSendEvent;
                gateway.messagesLog.OnClearMessages += OnClearMessages;
                gateway.OnNewNodeEvent += OnNewNodeEvent;
                gateway.OnNodeLastSeenUpdatedEvent += OnNodeLastSeenUpdatedEvent;
                gateway.OnNodeUpdatedEvent += OnNodeUpdatedEvent;
                gateway.OnNodeBatteryUpdatedEvent += OnNodeBatteryUpdatedEvent;
                gateway.OnNewSensorEvent += OnNewSensorEvent;
                gateway.OnSensorUpdatedEvent += OnSensorUpdatedEvent;
                gateway.OnClearNodesListEvent += OnClearNodesListEvent;
                gateway.OnDisconnectedEvent += OnGatewayDisconnectedEvent;
                gateway.OnConnectedEvent += OnGatewayConnectedEvent;

                if (OnConnected != null && IsConnected())
                    OnConnected(this, null);

                // DebugState("Connected.");

                return true;
            }
            catch
            {
                DebugState("Can`t connect.");
                if (OnConnectionFailed != null)
                    OnConnectionFailed(this, null);
                return false;
            }
        }
		public async Task Connect()
		{
			_hubConnection = new HubConnection(ConfigurationManager.AppSettings["ServerPath"]);
			_hubConnection.Headers.Add("login", _accessProvider.Login);
			_hubConnection.Headers.Add("token", _accessProvider.Token);
			_hubProxy = _hubConnection.CreateHubProxy("waiterHub");
			_hubProxy.On<OrderModel>("NewOrderMade", order => _waiterApp.NewOrderMade(order));
			_hubProxy.On<IEnumerable<OrderModel>>("OrdersAwaiting", awaitingOrders => _waiterApp.OrdersAwaiting(awaitingOrders));
			_hubProxy.On<AcceptedOrderCurrentStateModel>("AcceptedOrderInfoUpdated", acceptedOrder => _waiterApp.AcceptedOrderInfoUpdated(acceptedOrder));
			_hubProxy.On<AcceptOrderModel>("OrderWasAccepted", acceptedOrder => _waiterApp.OrderWasAccepted(acceptedOrder));
			_hubProxy.On<String>("CallWaiter", tableLogin => _waiterApp.CallWaiter(tableLogin));
			await _hubConnection.Start();
		}
Beispiel #20
0
        public static void Main()
        {
            Timer.Elapsed += Elapsed;
            Timer.Start();
            _hubConnection = new HubConnection("http://localhost:50025");
            _conversationProxy = _hubConnection.CreateHubProxy("RecycleHub");
            _conversationProxy.On("Broadcast", message => Console.WriteLine(message));
            _conversationProxy.On("Online", message => Console.WriteLine(message));

            _hubConnection.Closed += HubConnectionOnClosed;
            _hubConnection.StateChanged += HubConnectionStateChanged;
            ConnectToHub();
            Console.ReadLine();
        }
        public ConnectionManager(IDispatcher dispatcher)
        {
            _dispatcher = dispatcher;

            var hub = new HubConnection("http://signallines.apphb.com");

            _gameHub = hub.CreateProxy("GameHub");
            _gameHub.On("addMessage", ProcessMessage);
            _gameHub.On<int, int, int>("lineClicked", HandleLineClicked);
            _gameHub.On<Player>("newPlayerJoined", ProcessNewPlayerJoined);
            _gameHub.On<GameState>("resetGame", HandleResetGame);
            _gameHub.On<Player>("playerLeft", HandlePlayerLeft);

            hub.Start().Wait();
        }
Beispiel #22
0
        public ChatHubProxy(HubConnection connection, SynchronizationContext context)
        {
            _connection = connection;
            _context = context;
            _proxy = _connection.CreateHubProxy("ChatHub");

            _proxy.On<UserDetail, ChatMessage>("OnMessageReceived", OnMessageReceived);
            MessageReceived = (sender, message) => { };

            _proxy.On<UserDetail, UserDetail[]>("OnConnected", OnConnected);
            Connected = (userdetail, userdetails) => { };

            _proxy.On<UserDetail>("OnNewUserConnected", OnNewUserConnected);
            NewUserConnected = (userdetail) => { };
        }
 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 async Task Connect()
		{
			if (_hubConnection != null && _hubConnection.State == ConnectionState.Connected)
				return;

			_hubConnection = new HubConnection(ConfigurationManager.AppSettings["ServerPath"]);
			_hubConnection.Headers.Add("login", _accessProvider.Login);
			_hubConnection.Headers.Add("token", _accessProvider.Token);
			_hubProxy = _hubConnection.CreateHubProxy("tableHub");
			_hubProxy.On<string>("NotifyTable", message => _tableApp.NotifyTable(message));
			_hubProxy.On<EndOrderModel>("NotifyOrderEnded", endedOrder => _tableApp.NotifyOrderEnded(endedOrder));
			_hubProxy.On<int>("SendOrderId", id => _tableApp.SendOrderId(id));
			_hubProxy.On<OrderItemState>("NotifyOrderItemStateChanged", state => _tableApp.NotifyOrderItemStateChanged(state));
			_hubProxy.On<ReservationOrderScheduledModel>("LockTable", scheduledOrder => _tableApp.LockTable(scheduledOrder));
			await _hubConnection.Start();
		}
Beispiel #25
0
        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,
            };
        }
Beispiel #26
0
 // Constructor
 public MainPage()
 {
     _hubConnection = new HubConnection("http://signalrandiot.azurewebsites.net");
     _deviceHubProxy = _hubConnection.CreateHubProxy("DeviceDataHub");
     _deviceHubProxy.On<DeviceData>("NewDataRecieved", x =>
     {
         Dispatcher.BeginInvoke(() => 
         {
             if (x.DataType == "Temperature")
             {
                 ((ArrowGaugeIndicator)this.TempatureGauge.Indicators.Single(y => y.GetType() == typeof(ArrowGaugeIndicator))).Value = x.DataValue;
             }
             else if (x.DataType == "Humidity")
             {
                 ((ArrowGaugeIndicator)this.HumidityGauge.Indicators.Single(y => y.GetType() == typeof(ArrowGaugeIndicator))).Value = x.DataValue;
             }
             else if (x.DataType == "Light")
             {
                 ((ArrowGaugeIndicator)this.LightGauge.Indicators.Single(y => y.GetType() == typeof(ArrowGaugeIndicator))).Value = x.DataValue;
             }
             else if (x.DataType == "Distance")
             {
                 ((ArrowGaugeIndicator)this.DistanceGauge.Indicators.Single(y => y.GetType() == typeof(ArrowGaugeIndicator))).Value = x.DataValue;
             }
         });
         
     });
     InitializeComponent();
     this._hubConnection.Start();
 }
Beispiel #27
0
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            DataContext = App.ViewModel;
            var hubConnection = new HubConnection("http://192.168.2.128:50188");
            chat = hubConnection.CreateHubProxy("chat");

            chat.On<string>("newMessage", msg => Dispatcher.BeginInvoke(() => App.ViewModel.Items.Add(new ItemViewModel { LineOne = msg })));

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

            var scheduler = TaskScheduler.FromCurrentSynchronizationContext();
            hubConnection.Start().ContinueWith(task =>
                {
                    var ex = task.Exception.InnerExceptions[0];
                    App.ViewModel.Items.Add(new ItemViewModel { LineOne = ex.Message });
                },
                CancellationToken.None,
                TaskContinuationOptions.OnlyOnFaulted,
                scheduler);
        }
        private void StartService()
        {
            try
            {

                if (_ProxyAuth != null)
                {
                    if (_ProxyAuth.Authenticated)
                    {
                        _Hub = new Microsoft.AspNet.SignalR.Client.HubConnection(RemoteDesktop_CSLibrary.Config.SignalRHubUrl);
                        _ProxyHub = _Hub.CreateHubProxy(RemoteDesktop_CSLibrary.Config.SignalRHubName);
                        _Hub.TransportConnectTimeout = new TimeSpan(0, 0, 4);
                        _ProxyHub.On<List<Client>>("AvailableClients", ReceivedClients);
                        _Hub.Error += _Hub_Error;
                        if (ProxyAuth.UsingWindowsAuth)
                        {
                            _Hub.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
                        }
                        else
                        {
                            _Hub.CookieContainer = new CookieContainer();
                            _Hub.CookieContainer.Add(_ProxyAuth.AuthCookie);
                        }
                        _Hub.Start();
                    }
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
            }
        }
Beispiel #29
0
        /// <summary>
        /// Hubをセットする
        /// </summary>
        /// <param name="hub"></param>
        public void SetHub(IHubProxy hub)
        {
            if(hub == null) throw new ArgumentNullException(nameof(hub));
            this.hub = hub;
            
            hub.On<string, Type>("serve",async (json, type) =>
              {
                  var noodles = lib.NoodleListConverter.Convert(json, type);
                  if(!noodles.Any()) return;
                  
                  ServedInformation = string.Join("\r\n", ServedInformation, $"{noodles.First().Name}が流れてきたよ!");
                  _flowing = true;

                  try
                  {
                      await Task.Delay(5000);
                      if(!_isPick)
                      {
                          await hub.Invoke("Picking", 0);
                          return;
                      }

                      var pickedCount = Guest.Picking(noodles);
                      ServedInformation = string.Join("\r\n", ServedInformation, Guest.Eat(noodles.Take(pickedCount)));
                      await hub.Invoke("Picking", pickedCount);
                  }
                  finally
                  {
                      _flowing = false;
                      _isPick = false;
                  }
              });
        }
Beispiel #30
0
        private void Initialize()
        {
            try
            {
                connection = new HubConnection(url);
                hub        = connection.CreateHubProxy("TickerHub");
                //await connection.Start();

                hub?.On("OnNextTick", x => OnNextTick(x));
            }
            catch (Exception ex)
            {
                Message = ex.Message;
            }
        }
Beispiel #31
0
        private static async Task RunAsync()
        {
            var       connection = new HubConnection("http://localhost:44914/");
            IHubProxy chat       = connection.CreateHubProxy("Chat");

            chat.On <string>("send", Console.WriteLine);

            await connection.Start();

            string line = null;
            await Task.Factory.StartNew(() =>
            {
                while (!String.IsNullOrEmpty(line = Console.ReadLine()))
                {
                    chat.Invoke("send", "Console: " + line);
                }
            });
        }
Beispiel #32
0
        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            var       hubCn = new HubConnection(txtServerUrl.Text);
            IHubProxy proxy = hubCn.CreateHubProxy("MyHub");

            proxy.On <string>("hello", (message) =>
            {
                TaskbarIcon notifyIcon = (TaskbarIcon)FindResource("MyNotifyIcon");
                MainWindow._messages.Add(message);
                notifyIcon.ShowBalloonTip("Alert", message, BalloonIcon.Info);
            });
            hubCn.Start().Wait();

            App.ServerUrl = txtServerUrl.Text;
            App.Current.MainWindow.Show();

            this.Close();
        }
Beispiel #33
0
        public async static void ConnectToHub()
        {
            if (!string.IsNullOrEmpty(endpoint) && !string.IsNullOrEmpty(hubName))
            {
                connection = new HubConnection(endpoint);
                proxy      = connection.CreateHubProxy(hubName);


                // setup Methods and Link

                // Has to be the same call as the hub
                proxy.On("RecieveMessage", new Action <string, string>(OnRecieveMessage));

                //Connect to server
                connection.Received += Connection_Recieved;
                await connection.Start();// Waits For task to complete
            }
        }
        public void OnConnect()
        {
            CloseConnection();
            _hubConnection         = new HubConnection(ServerURI);
            _hubConnection.Closed += HubConnectionClosed;
            _hubProxy              = _hubConnection.CreateHubProxy("GroupChatHub");
            _hubProxy.On <string, string, string>("MessageToGroup", OnMessageReceived);

            try
            {
                _hubConnection.Start();
            }
            catch (HttpRequestException ex)
            {
                _messagingService.ShowMessage(ex.Message);
            }
            _messagingService.ShowMessage("client connected");
        }
        public MainPage()
        {
            InitializeComponent();

            // create connection
            var hubConnection = new HubConnection("http://signalrmeetupdemo.azurewebsites.net/signalr");

            // create proxy
            loungeProxy = hubConnection.CreateHubProxy("Lounge");

            loungeProxy.On <string>("pongHello",
                                    data =>
                                    Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                                        () => { pongTxt.Text += Environment.NewLine + data; })
                                    );

            hubConnection.Start().Wait();
        }
Beispiel #36
0
        /// <summary>
        /// Realiza la configuración inicial de signalR para este viewmodel.
        /// </summary>
        private async void SignalR()
        {
            proxy = Connection.Connection.proxy;
            conn  = Connection.Connection.conn;

            proxy.On <List <clsQuestion> >("sendQuestions", receiveQuestions);
            proxy.On <bool, int>("sendIsCorrect", receiveIsCorrect);
            proxy.On <bool, int>("sendRivalIsCorrect", receiveIsCorrectRival);
            proxy.On <String, String, List <clsQuestion> >("comenzarPartida", comenzarPartida);
            proxy.On <int, int, int, int>("mandarEstadisticasFinalPartida", receiveMatchStats);

            proxy.On <int>("questionBeingPlayed", receiveQuestionBeingPlayed);
        }
Beispiel #37
0
        async private void makeConnection()
        {
            try
            {
                // Pass parameter form client to server.
                var querystringData = new Dictionary <string, string>();
                querystringData.Add("chatversion", "1.1");

                var hubConnection = new HubConnection("http://localhost:53748", querystringData);

                // Windows authentication.
                hubConnection.Credentials = CredentialCache.DefaultCredentials;
                // Connection Header.
                //  hubConnection.Headers.Add("myauthtoken", /* token data */);
                //// Auth(Certificate).
                //hubConnection.AddClientCertificate(X509Certificate.CreateFromCertFile("MyCert.cer"));

                chat          = hubConnection.CreateHubProxy("ChatHub");
                chatShow.Text = "";
                Context       = SynchronizationContext.Current;

                chat.On <string, string>("broadcastMessage",
                                         (name, message) =>
                                         Context.Post(delegate
                {
                    this.chatShow.Text += name + ": "; this.chatShow.Text += message + "\n";
                }, null)
                                         );

                chat.Subscribe("notifyWrongVersion").Received += notifyWrongVersion_chat;



                await hubConnection.Start();

                await chat.Invoke("Notify", chatName.Text, hubConnection.ConnectionId);
            }
            catch (HubException ex)
            {
            }
            catch (Exception ex)
            {
            }
        }
Beispiel #38
0
        static void Main(string[] args)
        {
            string    msg = null;
            DataTable dados;

            var       hubConnection = new HubConnection("http://localhost:54132/");
            IHubProxy serverHub     = hubConnection.CreateHubProxy("BroadcastHub");

            serverHub.On <RequisicaoSql>("obterConsulta", (requisicao) =>
            {
                //RequisicaoSql requisicao = ProcessamentoBroadcast.DeserializaRequisicaoSql(requisicaoJSON);
                if (requisicao.CodigoUsuario == 45)
                {
                    Console.WriteLine($"Horário disparo: {requisicao.DataHoraRequisicao}");
                    Console.WriteLine($"Horário recebimento: {DateTime.Now:G}");
                    Console.WriteLine($"SQL Recebido: {requisicao.ComandoSql}");
                    Console.WriteLine($"Código Requisição: {requisicao.CodigoRequisicao}");
                    Console.WriteLine($"Tipo Consulta: {requisicao.Tipo}");
                    Console.WriteLine($"Parametros:");
                    foreach (var parametro in requisicao.Parametros)
                    {
                        Console.WriteLine($"    Nome: {parametro.Nome}, Valor: {parametro.Valor}, Tipo: {parametro.Tipo}");
                    }

                    RespostaRequisicaoSql resposta = Conexao.ObterDados(requisicao.ComandoSql, requisicao.Parametros);

                    resposta.CodigoRequisicaoSql = requisicao.CodigoRequisicao;
                    resposta.Parametros          = ProcessamentoBroadcast.CriarParametros();

                    serverHub.Invoke("devolverDados", resposta);
                }
            }
                                         );

            hubConnection.Start().Wait();

            serverHub.Invoke("Notify", "Console app", hubConnection.ConnectionId);


            while ((msg = Console.ReadLine()) != null)
            {
                return;
            }
        }
        public async Task ConnectAsync()
        {
            _connection = new HubConnection(url);
            _hubProxy   = _connection.CreateHubProxy("OrderBook");
            _hubProxy.On <User>("UserLogin", (u) => UserLoggedIn?.Invoke(u));
            _hubProxy.On <string>("UserLogout", (n) => UserLoggedOut?.Invoke(n));
            _hubProxy.On <string>("UserDisconnection", (n) => UserDisconnected?.Invoke(n));
            _hubProxy.On <string>("UserReconnection", (n) => UserReconnected?.Invoke(n));
            _hubProxy.On <IEnumerable <Order> >("BroadcastOrders", (n) => ReceiveNewOrder?.Invoke(n));
            _hubProxy.On <string, MessageType>("NotifyUser", (n, m) => ReceiveNotification?.Invoke(n, m));
            _hubProxy.On <string>("SendBidDepth", (x) => ReceiveBidDepth?.Invoke(x));
            _hubProxy.On <string>("SendAskDepth", (x => ReceiveAskDepth?.Invoke(x)));

            _connection.Reconnecting += Reconnecting;
            _connection.Reconnected  += Reconnected;
            _connection.Closed       += Disconnected;

            ServicePointManager.DefaultConnectionLimit = 10;
            await _connection.Start();
        }
Beispiel #40
0
        public async Task ConnectAsync()
        {
            hubConnection = new HubConnection(this.ServerURI);
            // hubConnection.Closed += hubConnection_Closed;
            hubProxy = hubConnection.CreateHubProxy("ChatHub");

            //Handle incoming event from server: use Invoke to write to console from SignalR's thread
            hubProxy.On <string, string>("BroadcastMessage", (sender, message) =>
                                         this.Dispatcher.Invoke(() =>
                                                                PrintMessage(sender, message)));

            hubProxy.On <string, string>("BroadcastMessage", (sender, message) =>
                                         this.Dispatcher.Invoke(() =>
                                                                m_data.notifycount++));

            hubProxy.On <string, string>("BroadcastMessage", (sender, message) =>
                                         this.Dispatcher.Invoke(() =>
                                                                ShowStandardBalloon(String.Format("{0}: {1}" + Environment.NewLine, sender, message))));


            hubProxy.On <string>("whoIsOn", (grps) =>
                                 this.Dispatcher.Invoke((Action)(() => names2 = (String.Format("{0}", grps)))));

            hubProxy.On <string>("whoIsOn", (grps) =>
                                 this.Dispatcher.Invoke((Action)(() => SplitUsers())));

            hubProxy.On <string>("whoIsOn", (grps) =>
                                 this.Dispatcher.Invoke((Action)(() => names1 = (String.Format("{0}", grps)))));

            try
            {
                await hubConnection.Start().ContinueWith((antecedent) =>
                {
                    hubProxy.Invoke("getMyName", this.ConnectedUser);
                });
            }
            catch (HttpRequestException)
            {
                // StatusText.Text = "Unable to connect to server: Start server before connecting clients.";
                //No connection: Don't enable Send button or show chat UI
                return;
            }


            /*
             * SignInPanel.Visible = false;
             * ChatPanel.Visible = true;
             * TextBoxMessage.Focus();
             */
            ServerName.Text = ("Connected to server at " + ServerURI + "  Default Username is " + ConnectedUser + Environment.NewLine);
        }
Beispiel #41
0
        public async Task ConnectAsync()
        {
            connection = new HubConnection(url);
            hubProxy   = connection.CreateHubProxy("ChatHub");
            hubProxy.On <User>("ParticipantLogin", (u) => ParticipantLoggedIn?.Invoke(u));
            hubProxy.On <string>("ParticipantLogout", (n) => ParticipantLoggedOut?.Invoke(n));
            hubProxy.On <string>("ParticipantDisconnection", (n) => ParticipantDisconnected?.Invoke(n));
            hubProxy.On <string>("ParticipantReconnection", (n) => ParticipantReconnected?.Invoke(n));
            hubProxy.On <string, string>("BroadcastTextMessage", (n, m) => NewTextMessage?.Invoke(n, m, MessageType.Broadcast));
            hubProxy.On <string, byte[]>("BroadcastPictureMessage", (n, m) => NewImageMessage?.Invoke(n, m, MessageType.Broadcast));
            hubProxy.On <string, string>("UnicastTextMessage", (n, m) => NewTextMessage?.Invoke(n, m, MessageType.Unicast));
            hubProxy.On <string, byte[]>("UnicastPictureMessage", (n, m) => NewImageMessage?.Invoke(n, m, MessageType.Unicast));
            hubProxy.On <string>("ParticipantTyping", (p) => ParticipantTyping?.Invoke(p));

            connection.Reconnecting += Reconnecting;
            connection.Reconnected  += Reconnected;
            connection.Closed       += Disconnected;

            ServicePointManager.DefaultConnectionLimit = 10;
            client = new Client();
            await client.Start();

            //await connection.Start();
        }
Beispiel #42
0
        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // create input engine
            new InputEngine(this);
            new FadeTextManager(this);
            new ChatTextManager(this);
            new Leaderboard(this);
            _tManager = new TileManager();
            cam       = new Camera(Vector2.Zero,
                                   new Vector2(tileMap.GetLength(1) * tileWidth, tileMap.GetLength(0) * tileHeight));


            // TODO: Add your initialization logic here change local host to newly created local host

            serverConnection = new HubConnection("http://cgmazerunner.azurewebsites.net");
            serverConnection.StateChanged += ServerConnection_StateChanged;
            proxy = serverConnection.CreateHubProxy("GameHub");
            serverConnection.Start();


            Action <PlayerData> joined = clientJoined;

            proxy.On <PlayerData>("Joined", joined);

            Action <string> Leave = clientleft;

            proxy.On <string>("left", Leave);

            Action <List <PlayerData> > currentPlayers = clientPlayers;

            proxy.On <List <PlayerData> >("CurrentPlayers", currentPlayers);

            Action <string> _Chat = writeChat;

            proxy.On <string>("chat", _Chat);

            Action <string> LeaderB = writeLeaderboard;

            proxy.On <string>("leader", LeaderB);

            Action <string, Position> otherMove = clientOtherMoved;

            proxy.On <string, Position>("OtherMove", otherMove);



            // Add the proxy client as a Game service o components can send messages
            Services.AddService <IHubProxy>(proxy);

            base.Initialize();
        }
Beispiel #43
0
        public void Init()
        {
            if (_isInitialized)
            {
                return;
            }
            _isInitialized = true;

            _hubConnection = new HubConnection(Secrets.GoHubUrl);
            _goHub         = _hubConnection.CreateHubProxy("GoHub");

            _goHub.On(nameof(UserConnected), (UserPrefs user) => UserConnected?.Invoke(user));
            _goHub.On(nameof(UserDisconnected), (string user) => UserDisconnected?.Invoke(user));

            _goHub.On(nameof(LobbyPost), (Post post) => LobbyPost?.Invoke(post));
            _goHub.On(nameof(GamePost), (Post post) => GamePost?.Invoke(post));

            _goHub.On(nameof(GameRequested), (string name) => GameRequested?.Invoke(name));
            _goHub.On(nameof(GameRequestDeclined), (string name) => GameRequestDeclined?.Invoke(name));
            _goHub.On(nameof(GameRequestCancelled), (string name) => GameRequestCancelled?.Invoke(name));
            _goHub.On(nameof(GameRequestAccepted), (string name) => GameRequestAccepted?.Invoke(name));

            _goHub.On(nameof(GameAborted), (string name) => GameAborted?.Invoke(name));
        }
Beispiel #44
0
        private async void TestEmoConnection()
        {
            // Establish a connection to our Hub.  The Hub is created in EmotivBridgeClassic
            var hubConnection = new HubConnection("http://localhost:16566/");

            // Get a proxy to our hub instance.
            IHubProxy emotiveProxy = hubConnection.CreateHubProxy("EmotivBridgeHub");

            // Wire up the UpdateEmotion event.  When the server fires this event, it will call this code.
            emotiveProxy.On("UpdateEmotion",
                            emo =>
            {
                // Not the best way to parse this data.  JObject is from JSON.NET
                // http://www.newtonsoft.com/json
                var data = emo as JObject;
                Debug.WriteLine(String.Format("My new emotion is {0} with magnitude {1} ",
                                              Enum.Parse(typeof(EmotivEmotion),
                                                         data.SelectToken("Emotion").ToString()).ToString(),
                                              data.SelectToken("Magnitude").ToString()).ToString()
                                );

                // fix to use enum
                String currentEmotion = Enum.Parse(typeof(EmotivEmotion), data.SelectToken("Emotion").ToString()).ToString();
                if (currentEmotion == "ANGRY")
                {
                    _spheroController.ChangeColor(SpheroColor.RED);
                }
                else if (currentEmotion == "HAPPY")
                {
                    _spheroController.ChangeColor(SpheroColor.GREEN);
                }
                else
                {
                    _spheroController.ChangeColor(SpheroColor.WHITE);
                }
            });

            // Start the controller and kick off the listening
            // Find InitializeController in EmotivServer
            await hubConnection.Start();

            await emotiveProxy.Invoke("InitializeController");
        }
Beispiel #45
0
        static void Main(string[] args)
        {
            HubConnection hub   = new HubConnection("http://localhost:64277");
            IHubProxy     proxy = hub.CreateHubProxy("TimeQuery");

            proxy.On("addMessage", message =>
            {
                Console.WriteLine(message);
            });

            hub.Start().Wait();
            proxy.Invoke("StartTimer");

            string line = null;

            while ((line = Console.ReadLine()) != null)
            {
            }
        }
        static void Main(string[] args)
        {
            HubConnection connection = new HubConnection("http://localhost:56859");

            proxy = connection.CreateHubProxy("UserInputHub");

            //connection.Received += Connection_Received;

            Action <int> sendPlayerNum = recieved_player_num;

            Action <string, string> SendMessagerecieved = recieved_a_message;
            Action <bool>           sendValidated       = recieved_validated;

            proxy.On("BroadcastMessage", SendMessagerecieved);
            connection.Start().Wait();


            ModelUsers1    db  = new ModelUsers1();
            UsersViewModel uvm = new UsersViewModel();

            //UsersDb db = new UsersDb();
            name     = null;
            password = null;

            Console.Write("User Name:");
            name = Console.ReadLine();

            Console.Write("\nPassword:"******"Please fill in all the details.");
            }

            if (name != null || password != null)
            {
                proxy.Invoke("RequestValidation", new object[] { name, password });
                proxy.Invoke("RequestValidated");
            }

            //ServerSide.Models.UsersDb
        }
Beispiel #47
0
        public async void StartHub()
        {
            var       hubConnection  = new HubConnection("http://localhost:5263/signalr");
            IHubProxy tickerHubProxy = hubConnection.CreateHubProxy("TickerHub");

            await hubConnection.Start();

            SendSubscription(tickerHubProxy).Wait();



            tickerHubProxy.On <IEnumerable <TickerDto> >("SendTickers", tickers =>
            {
                foreach (var ticker in tickers)
                {
                    Console.WriteLine("Stock update for '{0}' new price {1}", ticker.Name, ticker.Price);
                }
            });
        }
        public MainPage()
        {
            this.InitializeComponent();
            Messages.Add("Connecting...");
            _hubConnection         = new HubConnection(ServerURI);
            _hubConnection.Closed += HubConnectionClosed;
            _hubProxy              = _hubConnection.CreateHubProxy("ChatHub");
            _hubProxy.On <string, string>("BroadcastMessage", OnMessageReceived);

            try
            {
                _hubConnection.Start();
            }
            catch (HttpRequestException ex)
            {
                Messages.Add(ex.Message);
            }
            Messages.Add("client connected");
        }
        public SignalConnector(Action <Response> listener)
        {
            OnMessageReceived = listener;

            chatConnection = new HubConnection("http://chatsignalrtst.apphb.com/", true);
            SignalRChatHub = chatConnection.CreateHubProxy("ChatHub");

            SignalRChatHub.On <string, string>("addNewMessageToPage", (timestamp, message) =>
            {
                if (OnMessageReceived != null)
                {
                    var response = new Response()
                    {
                        Size = MeasureSize(message), Delay = MeasureDelay(timestamp), Message = message
                    };
                    listener(response);
                }
            });
        }
Beispiel #50
0
        public async Task Connect(string url, Action <MessageDto> callback)
        {
            connection = connection ?? new HubConnection(url);

            proxy = proxy ?? connection.CreateHubProxy(nameof(GameHub));

            proxy.On <string>("SendMessage", messageJson =>
            {
                callback(JsonConvert.DeserializeObject <MessageDto>(messageJson, new JsonSerializerSettings
                {
                    TypeNameHandling    = TypeNameHandling.Auto,
                    ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
                }));
            });

            await connection.Start();

            await proxy.Invoke("SendToHost", new MessageDto { MessageType = Core.Enums.MessageType.InitialConnection });
        }
Beispiel #51
0
        public async Task HubProgressThrowsInvalidOperationExceptionIfAttemptToReportProgressAfterMethodReturn(HostType hostType, TransportType transportType, MessageBusType messageBusType)
        {
            using (var host = CreateHost(hostType, transportType))
            {
                host.Initialize(messageBusType: messageBusType);

                HubConnection hubConnection = CreateHubConnection(host);
                IHubProxy     proxy         = hubConnection.CreateHubProxy("progress");

                proxy.On <bool>("sendProgressAfterMethodReturnResult", result => Assert.True(result));

                using (hubConnection)
                {
                    await hubConnection.Start(host.Transport);

                    await proxy.Invoke <int>("SendProgressAfterMethodReturn", _ => { });
                }
            }
        }
Beispiel #52
0
        public ServerEventsManager(string apiUri)
        {
            IDictionary <string, string> queryString = new Dictionary <string, string>
            {
                ["id"] = _id.ToString()
            };

            _hubConnection = new HubConnection(apiUri, queryString);
            _hubConnection.StateChanged   += HubConnection_StateChanged;
            _hubConnection.Closed         += HubConnection_Closed;
            _hubConnection.ConnectionSlow += HubConnection_ConnectionSlow;
            _hubConnection.Error          += HubConnection_Error;
            _hubConnection.Received       += HubConnection_Received;
            _hubConnection.Reconnected    += HubConnection_Reconnected;
            _hubConnection.Reconnecting   += HubConnection_Reconnecting;
            _hubProxy = _hubConnection.CreateHubProxy("UpdatesHub");
            _hubProxy.On <TypeOfInterest>(nameof(IClient.Updated), OnUpdated);
            Console.WriteLine($"Created {nameof(ServerEventsManager)} with id={_id}");
        }
        public async void On1()
        {
            using (HubConnection connection = new HubConnection(BaseUrl))
            {
                IHubProxy hubProxy = connection.CreateHubProxy("TestHub");
                await connection.Start();

                ManualResetEvent resetEvent = new ManualResetEvent(false);

                int value1 = 0;

                hubProxy.On <int>("ClientCallback", (v1) => { value1 = v1; resetEvent.Set(); });

                await hubProxy.Invoke("InvokeClientCallback1", 1);

                Assert.True(resetEvent.WaitOne(3000));
                Assert.Equal(1, value1);
            }
        }
Beispiel #54
0
        async Task RegisterPC(ComputerInfo computer)
        {
            hubCnn = new HubConnection("http://*****:*****@"temp.txt", true))
                {
                    outfile.WriteLine(msg);
                }
            });
            await hubCnn.Start();

            await hubProxy.Invoke("RegisterPCClient", computer.Make, computer.Model);
        }
Beispiel #55
0
 public void Configuration(IAppBuilder app)
 {
     if (ConfigurationManagerHelper.GetValueOnKey("stardust.UseAzureAd") == "true")
     {
         ConfigureAuth(app);
     }
     if (ConfigurationManagerHelper.GetValueOnKey("stardust.UseRealtimeUpdate") == "true")
     {
         app.MapSignalR("/signalr", new HubConfiguration
         {
             EnableJSONP             = true,
             EnableDetailedErrors    = true,
             EnableJavaScriptProxies = true
         });
         hub = GlobalHost.ConnectionManager.GetHubContext <ConfigSetHub>();
         Resolver.Activate <ICacheManagementService>().RegisterRealtimeNotificationService(
             (id, environment) =>
         {
             try
             {
                 Logging.DebugMessage("Sending update message {0}-{1}", id, environment);
                 hub.Clients.All.changed(id, environment);
             }
             catch (Exception ex)
             {
                 ex.Log();
             }
         });
         if (!Utilities.IsDevelopementEnv())
         {
             return;
         }
         hubConnection = new HubConnection("https://localhost:44305/");
         hubClient     = hubConnection.CreateHubProxy("configSetHub");
         hubClient.On(
             "changed",
             (string id, string environment) =>
         {
             Logging.DebugMessage("UpdateMessage: {0}-{1}", id, environment);
         });
         hubConnection.Start();
     }
 }
Beispiel #56
0
        // Connects to SignalR Server
        void connectSignalR()
        {
            _connection.Start(); // Starts SignalR Connection
                                 // Current message
            var toFront = txtSignalRMessage.Text;

            // Solves Cross threading issue
            var uiCtx = SynchronizationContext.Current;

            _hub.On("recieveMessage", x =>
            {
                // You are no longer on the UI thread, so you have to post back to it
                uiCtx.Post(_ =>
                {
                    // Put all code that touches the UI here
                    hubMessages(x);
                }, null);
            });
        }
Beispiel #57
0
        public IObservable <PriceDto> GetSpotStreamForConnection(string currencyPair, IHubProxy pricingHubProxy)
        {
            return(Observable.Create <PriceDto>(
                       observer =>
            {
                // subscribe to price feed first, otherwise there is a race condition
                var priceSubscription = pricingHubProxy.On <PriceDto>(
                    "OnNewPrice",
                    p =>
                {
                    if (p.Symbol == currencyPair)
                    {
                        observer.OnNext(p);
                    }
                });

                // send a subscription request
                Console.WriteLine("Sending price subscription for currency pair {0}", currencyPair);
                var subscription =
                    SendSubscription(currencyPair, pricingHubProxy)
                    .Subscribe(_ => Console.WriteLine("Subscribed to {0}", currencyPair), observer.OnError);

                var unsubscriptionDisposable = Disposable.Create(
                    () =>
                {
                    // send unsubscription when the observable gets disposed
                    Console.WriteLine("Sending price unsubscription for currency pair {0}", currencyPair);
                    SendUnsubscription(currencyPair, pricingHubProxy)
                    .Subscribe(
                        _ => Console.WriteLine("Unsubscribed from {0}", currencyPair),
                        ex =>
                        Console.WriteLine(
                            "An error occurred while sending unsubscription request for {0}:{1}",
                            currencyPair,
                            ex.Message));
                });

                return new CompositeDisposable {
                    priceSubscription, unsubscriptionDisposable, subscription
                };
            }).Publish().RefCount());
        }
        public async Task ConnectAsync()
        {
            connection = new HubConnection(string.Format(url, "127.0.0.1", "8080"));
            hubProxy   = connection.CreateHubProxy("ChatHub");
            hubProxy.On <User>("ParticipantLogin", (u) => ParticipantLoggedIn?.Invoke(u));
            hubProxy.On <string>("ParticipantLogout", (n) => ParticipantLoggedOut?.Invoke(n));
            hubProxy.On <string>("ParticipantDisconnection", (n) => ParticipantDisconnected?.Invoke(n));
            hubProxy.On <string>("ParticipantReconnection", (n) => ParticipantReconnected?.Invoke(n));
            hubProxy.On <string, string>("BroadcastMessage", (n, m) => NewMessage?.Invoke(n, m, MessageType.Broadcast));
            hubProxy.On <string, string>("UnicastMessage", (n, m) => NewMessage?.Invoke(n, m, MessageType.Unicast));
            hubProxy.On <string, string, string>("SetNewTask", (n, m, k) => SetNewTask?.Invoke(n, m, k));
            connection.Reconnecting += Reconnecting;
            connection.Reconnected  += Reconnected;
            connection.Closed       += Disconnected;

            ServicePointManager.DefaultConnectionLimit = 10;
            await connection.Start();
        }
Beispiel #59
0
        public PictureView()
        {
            this.InitializeComponent();
            InitializeVideo();
            InitializeGPIO();

            // SignalR connection
            var       hubConnection    = new HubConnection("http://iotlock-api.azurewebsites.net");
            IHubProxy lightingHubProxy = hubConnection.CreateHubProxy("LightingHub");

            lightingHubProxy.On <string>("toggle", room =>
            {
                GpioPinValue value;
                switch (room)
                {
                case "hallway":
                    value = hallwayPin.Read() == GpioPinValue.Low ? GpioPinValue.High : GpioPinValue.Low;
                    hallwayPin.Write(value);
                    hallwayPin.SetDriveMode(GpioPinDriveMode.Output);
                    break;

                case "kitchen":
                    value = kitchenPin.Read() == GpioPinValue.Low ? GpioPinValue.High : GpioPinValue.Low;
                    kitchenPin.Write(value);
                    kitchenPin.SetDriveMode(GpioPinDriveMode.Output);
                    break;

                case "garden":
                    value = gardenPin.Read() == GpioPinValue.Low ? GpioPinValue.High : GpioPinValue.Low;
                    gardenPin.Write(value);
                    gardenPin.SetDriveMode(GpioPinDriveMode.Output);
                    break;

                case "bedroom":
                    value = bedroomPin.Read() == GpioPinValue.Low ? GpioPinValue.High : GpioPinValue.Low;
                    bedroomPin.Write(value);
                    bedroomPin.SetDriveMode(GpioPinDriveMode.Output);
                    break;
                }
            });
            hubConnection.Start();
        }
        public bool Initialize(string cacheName, string clientId, string connection, Action<string, string> onExpireCache, Action<string, string, string> onMessage, Action<Exception> onError)
        {
            var connectionDict = connection.ToObject<Dictionary<string, object>>();

            _cacheName = cacheName;
            ClientId = clientId;
            _url = connectionDict.GetSetting("url", "");

            _hubConnection = new HubConnection(_url);
            _proxy = _hubConnection.CreateHubProxy("CacheHub");
            _proxy.On<string, string, string>("serverMessage", (cid, clientName, message) =>
            {
                Debug.WriteLine(message);
                if (onMessage != null)
                    onMessage(cid, clientName, message);
            });

            _proxy.On<string, string>("expireCache", onExpireCache);

            _hubConnection.ConnectionSlow += () =>
            {
                Debug.WriteLine("Connection problems...");
            };
            _hubConnection.Error += onError;

            _hubConnection.Start().Wait();

            return true;
        }