A Connection for interacting with Hubs.
Inheritance: Connection, IHubConnection
Example #1
4
        private async Task ConnectToSignalR()
        {
            hubConnection = new HubConnection(App.MobileService.ApplicationUri.AbsoluteUri);

            if (user != null)
            {
                hubConnection.Headers["x-zumo-auth"] = user.MobileServiceAuthenticationToken;
            }
            else
            {
                hubConnection.Headers["x-zumo-application"] = App.MobileService.ApplicationKey;
            }

            proxy = hubConnection.CreateHubProxy("ChatHub");
            await hubConnection.Start();

            proxy.On<string>("helloMessage", async (msg) =>
             {
                 await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                 {
                     message += " " + msg;
                     Message.Text = message;
                 });

             });
        }
        public async Task SendToGroupFromOutsideOfHub()
        {
            using (var host = new MemoryHost())
            {
                IHubContext<IBasicClient> hubContext = null;
                host.Configure(app =>
                {
                    var configuration = new HubConfiguration
                    {
                        Resolver = new DefaultDependencyResolver()
                    };

                    app.MapSignalR(configuration);
                    hubContext = configuration.Resolver.Resolve<IConnectionManager>().GetHubContext<SendToSome, IBasicClient>();
                });

                var connection1 = new HubConnection("http://foo/");

                using (connection1)
                {
                    var wh1 = new AsyncManualResetEvent(initialState: false);

                    var hub1 = connection1.CreateHubProxy("SendToSome");

                    await connection1.Start(host);

                    hub1.On("send", wh1.Set);

                    hubContext.Groups.Add(connection1.ConnectionId, "Foo").Wait();
                    hubContext.Clients.Group("Foo").send();

                    Assert.True(await wh1.WaitAsync(TimeSpan.FromSeconds(10)));
                }
            }
        }
Example #3
0
        private async void StartConnection()
        {
            // Connect to the server
            try
            {
                var hubConnection = new HubConnection("http://192.168.0.43:61893/");

                // Create a proxy to the 'ChatHub' SignalR Hub
                chatHubProxy = hubConnection.CreateHubProxy("ChatHub");

                // Wire up a handler for the 'UpdateChatMessage' for the server
                // to be called on our client
                chatHubProxy.On<string,string>("broadcastMessage", (name, message) => {
                    var str = $"{name}:{message}\n";
                RunOnUiThread(()=>     text.Append( str ) );
                });


                // Start the connection
                await hubConnection.Start();


            }
            catch (Exception e)
            {
                text.Text = e.Message;
            }
        }
        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);
            }
        }
Example #5
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");
        }
Example #6
0
        static void Main(string[] args)
        {
            Task.Run(async () =>
            {
                var conHub = new HubConnection("http://localhost:8080/");
                conHub.CreateHubProxy("Shell").On<ShellCommandParams>("cmd", (data) =>
                {
                });

                using (var con = new Connection("http://localhost:8080/api/cmd"))
                {
                    con.Received += (data) =>
                    {
                        Console.WriteLine($"ola, recebi! {data}");
                    };
                    con.StateChanged += (state) =>
                    {
                        if (state.NewState != state.OldState)
                        {
                            Console.WriteLine($"De {state.OldState} para {state.NewState}");
                        }
                    };
                    await con.Start();

                    await con.Send("Hello Mello");
                }
            }).Wait();

        }
Example #7
0
        /// <summary>
        /// Setups the notifications.
        /// </summary>
        public async void SetupNotifications(Action action)
        {
            var hubConnection = new HubConnection(Application.Current.Host.Source.GetComponents(UriComponents.Scheme | UriComponents.HostAndPort, UriFormat.Unescaped));
            var proxy = hubConnection.CreateHubProxy(CommunicationConstants.RuntimeHubName);

            proxy.On<int>(
                CommunicationConstants.ActionsChangedEventName,
                personId =>
                    {
                        if (personId == Utils.CurrentUserPersonId || personId == CommunicationConstants.BroadcastPersonId)
                        {
                            Deployment.Current.Dispatcher.BeginInvoke(action);
                        }
                    });

            hubConnection.TraceWriter = Console.Out;

            try
            {
                await hubConnection.Start();
            }
            catch (Exception ex)
            {
                Logger.Log(LogSeverity.Error, "SignalR Hub Connection Error", ex);
            }
        }
Example #8
0
 public CrestLogger()
 {
     var hubConnection = new HubConnection("http://www.contoso.com/");
     errorLogHubProxy = hubConnection.CreateHubProxy("ErrorLogHub");
     //errorLogHubProxy.On<Error>("LogError", error => { });
     hubConnection.Start().Wait();
 }
        public async Task Start()
        {
            _hubConnection = new HubConnection("http://192.168.1.168/CodevelopService");
            //_hubConnection = new HubConnection(@"http://smartsolar.azurewebsites.net");
            var writer = new DebugTextWriter();
            _hubConnection.TraceLevel = TraceLevels.All;
            _hubConnection.TraceWriter = writer;
            _hubConnection.Error += _hubConnection_Error;
            _hubConnection.StateChanged += _hubConnection_StateChanged;


            // set up backchannel
            _hubProxy = _hubConnection.CreateHubProxy("DeviceFeedHub");

            _hubProxy.On<string>("hello", message =>
                LogMessage(message)
            );


            LogMessage("Starting");
            await _hubConnection.Start();


           /* MqttClient client = new MqttClient("192.168.1.168");
            client.Connect(_deviceId.ToString());
            client.Publish("/home/temperature", Encoding.UTF8.GetBytes("Starting"), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false);*/
        }
Example #10
0
        public void Start()
        {
            var siteUrl = Settings.Default.SiteUrl;
            var portNumber = Settings.Default.PortNumber;

            var uri = string.Format("http://*:{0}{1}", portNumber, siteUrl);

            const string url = "http://localhost:10000";
            StartOptions options = new StartOptions();
            options.Urls.Add(string.Format("http://{0}:10000", Environment.MachineName));
            options.Urls.Add("http://localhost:10000/");
            options.Urls.Add(uri);

            host = WebApp.Start<Startup>(options);

            var hubConnection = new HubConnection(url);
            var hubProxy = hubConnection.CreateHubProxy("MyHub");

            hubConnection.Start().ContinueWith(task =>
            {

            }).Wait();

            var timer = new Timer(x =>
            {
                if (ConnectionMapping.Count <= 1) return;

                hubProxy.Invoke("Send").Wait();
            }, null, 0, 2000);
        }
Example #11
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();
        }
Example #12
0
 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);
     }
 }
Example #13
0
 public void ConnectServer(string server, string port, string customerId, string accountId)
 {
     string ServerURI = server + ":" + port;
     //string ServerURI = "http://localhost:8080/";
     //if (Connection == null)
     Connection = new HubConnection(ServerURI);
     HubProxy = Connection.CreateHubProxy("ChatHub");
     try
     {
         Connection.Start().ContinueWith(task =>
         {
             if (task.IsFaulted)
             {
                 object[] obj = { false, "Can't connect to server." };
                 FireEvent("Login", obj);
             }
             else
             {
                 AuthenRequest(customerId, accountId);
             }
         });
     }
     catch (Exception ex)
     {
     }
 }
Example #14
0
        public MainWindow()
        {
            InitializeComponent();
            var hubConnection = new HubConnection("http://divewakeweb.azurewebsites.net/");
            stockTickerHubProxy = hubConnection.CreateHubProxy("WakeHub");
            hubConnection.Start().Wait();
            _sensor = KinectSensor.GetDefault();

            if (_sensor != null)
            {
                _sensor.Open();

                _bodies = new Body[_sensor.BodyFrameSource.BodyCount];

                _colorReader = _sensor.ColorFrameSource.OpenReader();
                _colorReader.FrameArrived += ColorReader_FrameArrived;
                _bodyReader = _sensor.BodyFrameSource.OpenReader();
                _bodyReader.FrameArrived += BodyReader_FrameArrived;

                // 2) Initialize the face source with the desired features
                _faceSource = new FaceFrameSource(_sensor, 0, FaceFrameFeatures.BoundingBoxInColorSpace |
                                                              FaceFrameFeatures.FaceEngagement |
                                                              FaceFrameFeatures.Glasses |
                                                              FaceFrameFeatures.LeftEyeClosed |
                                                              FaceFrameFeatures.PointsInColorSpace |
                                                              FaceFrameFeatures.RightEyeClosed);
                _faceReader = _faceSource.OpenReader();
                _faceReader.FrameArrived += FaceReader_FrameArrived;
            }
        }
 private void StartSignalRHubConnection()
 {
     //TODO: Specify your SignalR website settings in SCPHost.exe.config
     this.hubConnection = new HubConnection(ConfigurationManager.AppSettings["SignalRWebsiteUrl"]);
     this.twitterHubProxy = hubConnection.CreateHubProxy(ConfigurationManager.AppSettings["SignalRHub"]);
     hubConnection.Start().Wait();
 }
Example #16
0
		public async Task Connect(string uri)
		{
			var connection = new HubConnection(uri);
			connection.Closed += () =>
			{
				var eh = OnDisconnect;
				if (eh != null) eh();
			};
			var hubProxy = connection.CreateHubProxy("MyHub");
			hubProxy.On<string, string>("AddMessage", (userName, message) =>
			{
				var eh = On;
				if (eh != null) eh(userName, message);
			});
			try
			{
				await connection.Start();
			}
			catch (AggregateException e)
			{
				throw e.InnerException;
			}


			_connection = connection;
			_hubProxy = hubProxy;
		}
        public ListenerService()
        {
            InitializeComponent();
            
            // ReSharper disable once DoNotCallOverridableMethodsInConstructor
            EventLog.Log = "HubCollectorLog";
            StatsdClient = new Statsd(Config.Hostname, Config.Port);
            KlondikeConnections = new List<HubConnection>();

            Config.Hubs.ForEach(hub =>
            {
                var connection = new HubConnection(hub);

                IHubProxy statusHubProxy = connection.CreateHubProxy("status");
                statusHubProxy.On("updateStatus", status =>
                {
                    string name = Config.NameFromUrl(connection.Url);
                    var message = String.Format("From {2}: Status: {0}, Total: {1}", status.synchronizationState,
                        status.totalPackages, name);
                    EventLog.WriteEntry(message);
                    //Console.WriteLine(message);

                    StatsdClient.LogGauge("nuget."+ name +".packageCount", (int) status.totalPackages);
                });

                KlondikeConnections.Add(connection);
            });
        }
Example #18
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}");
            }
        }
        public async Task <bool> ConnectForSignalAsync(string hubName, TextWriter traceOutput = null)
        {
            HubConnection = new Microsoft.AspNet.SignalR.Client.HubConnection("http://serverdown.bogus.address.com", new Dictionary <string, string> {
                { "bearerToken", "Random" }
            });

            if (traceOutput != null)
            {
                HubConnection.TraceLevel = TraceLevels.All;

                HubConnection.TraceWriter = traceOutput;
            }

            HubProxy = HubConnection.CreateHubProxy(hubName);

            HubProxy.On <object>("OnEventMessage", OnEventMessage);
            try
            {
                await HubConnection.Start();

                return(true);
            }
            catch (HttpRequestException e)
            {
                return(false);
            }
        }
Example #20
0
        //[STAThread]
        static void Main(string[] args)
        {
            HubConnection hub = new HubConnection("http://localhost:57365/");

            var prxy=hub.CreateHubProxy("RemoteHub");
            prxy.On<string, string>("commandReceived", (command, parameters) => {
                Console.WriteLine(string.Format("Command : {0}, Parameters : {1} ", command, parameters));
                if ("executecommand".Equals(command, StringComparison.OrdinalIgnoreCase))
                {
                    System.Diagnostics.Process.Start("CMD.exe", "/C " + parameters);
                }
            });
            hub.Start().Wait();

            //var config = new HttpSelfHostConfiguration("http://localhost:4521");
            //System.Threading.Thread.Sleep(5000);
            //config.Routes.MapHttpRoute(
            //    "API Default", "api/{controller}/{id}",
            //    new { id = RouteParameter.Optional });

            //using (HttpSelfHostServer server = new HttpSelfHostServer(config))
            //{
            //    server.OpenAsync().Wait();
            //    Console.WriteLine("Press Enter to quit.");
            //    Console.ReadLine();
            //}
            Console.ReadLine();
        }
Example #21
0
        private async Task RunDemo(string url)
        {
            var hubConnection = new HubConnection(url);

            var querystringData = new Dictionary<string, string>();
            querystringData.Add("name", "primaveraServer");

            var connection = new HubConnection(url, querystringData);

            hubConnection.TraceWriter = _traceWriter;

            var hubProxy = hubConnection.CreateHubProxy("rhHub");
            hubProxy.On<string>("addChatMessage", (n) =>
            {
                //string n = hubProxy.GetValue<string>("index");
                hubConnection.TraceWriter.WriteLine("{0} ", n);
            });

            await hubConnection.Start();

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

            hubConnection.TraceWriter.WriteLine("Invoking long running hub method with progress...");
            await hubProxy.Invoke("SendChatMessage", new object[]   { "primaveraServer", "ola" });
            //hubConnection.TraceWriter.WriteLine("{0}", result);

            //await hubProxy.Invoke("multipleCalls");
        }
Example #22
0
        private async Task 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));

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

            await hubProxy.Invoke("DisplayMessageCaller", "Hello Caller!");

            string joinGroupResponse = await hubProxy.Invoke<string>("JoinGroup", hubConnection.ConnectionId, "CommonClientGroup");
            hubConnection.TraceWriter.WriteLine("joinGroupResponse={0}", joinGroupResponse);

            await hubProxy.Invoke("DisplayMessageGroup", "CommonClientGroup", "Hello Group Members!");

            string leaveGroupResponse = await hubProxy.Invoke<string>("LeaveGroup", hubConnection.ConnectionId, "CommonClientGroup");
            hubConnection.TraceWriter.WriteLine("leaveGroupResponse={0}", leaveGroupResponse);

            await hubProxy.Invoke("DisplayMessageGroup", "CommonClientGroup", "Hello Group Members! (caller should not see this message)");

            await hubProxy.Invoke("DisplayMessageCaller", "Hello Caller again!");
        }
Example #23
0
        static void Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                .WriteTo.ColoredConsole()
                .CreateLogger();

            string baseAddress = "http://*****:*****@ev}", channel, ev));
                hubConnection.Start().Wait();

                // Join the channel for task updates in our console window
                //
                eventHubProxy.Invoke("Subscribe", Constants.AdminChannel);
                eventHubProxy.Invoke("Subscribe", Constants.TaskChannel);

                Console.WriteLine($"Server is running on {baseAddress}");
                Console.WriteLine("Press <enter> to stop server");
                Console.ReadLine();

            }
        }
        private async void Connect()
        {
            Connection = new HubConnection(ServerURI);
            HubProxy = Connection.CreateHubProxy("NotifierHub");

            HubProxy.On<AlarmMessage>("SendNotification", async (notification) =>
            {
                await this.AlarmsList.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    this.AlarmsList.Items.Add(notification);
                });
            }
            );

            try
            {
                await Connection.Start();
            }
            catch (HttpRequestException)
            {
                return;
            }
            catch (Exception)
            {
                return;
            }
        }
        public Client(string platform)
        {
            _platform = platform;

            _connection = new HubConnection("http://meetupsignalrxamarin.azurewebsites.net/");
            _proxy = _connection.CreateHubProxy("ChatHub");
        }
Example #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();
 }
        public void Run()
        {
            System.Console.WriteLine("Starting connection to host at: {0} with launcher identifier name as {1}", AppSettings.HostUrl, AppSettings.LauncherName);

            var hubConnection = new HubConnection(AppSettings.HostUrl);
            IHubProxy hubProxy = hubConnection.CreateHubProxy("LauncherHub");
            hubProxy.On<LauncherCommand>("sendCommand", OnSendCommand);
            hubProxy.On<IEnumerable<LauncherSequence>>("sendSequence", OnSendSequence);
            ServicePointManager.DefaultConnectionLimit = 10;
            hubConnection.Start().Wait();

            hubConnection.StateChanged += change =>
            {
                System.Console.WriteLine("Connection to host state has changed to : " + change.NewState);
                if (change.NewState == ConnectionState.Connected)
                {
                    hubProxy.Invoke("Initialize", AppSettings.LauncherName);
                }
            };

            hubProxy.Invoke("Initialize", AppSettings.LauncherName);
            System.Console.WriteLine("Connection established.... waiting for commands from host...");
            while (true)
            {
                // let the app know we are health every 1000 (Ms = 1 second) * 60 sec = 1 min *
                Thread.Sleep(1000 * 60 * 5);
                hubProxy.Invoke("Initialize", AppSettings.LauncherName);
            }
        }
        public void ConnectToServer()
        {

            hubConnection = new HubConnection(serverAddress);
            hubProxy = hubConnection.CreateHubProxy("SoftNodesHub");
            bool isConnected = false;
            while (!isConnected)
            {
                try
                {
                    hubConnection.Start().Wait();
                    hubConnection.Closed += OnHubConnectionClosed;
                    //hubProxy.On<Message>("ReceiveMessage", ReceiveMessage);

                    isConnected = true;
                    LogInfo("Connected to server");
                    OnConnected?.Invoke();
                }
                catch (Exception e)
                {
                    LogError("Connection to server failed: " + e.Message);
                    OnConnectionFailed?.Invoke(e.Message);
                }
            }
        }
Example #29
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);
                }
            });
        }
 public void OpenConnection()
 {
     _connection = new HubConnection(_hubUrl);
     _alertHubProxy = _connection.CreateHubProxy("alertHub");
     _resourceHubProxy = _connection.CreateHubProxy("resourceHub");
     _connection.Start().Wait();
 }
 public async static Task<IHubProxy> GetProxy(String hubName)
 {
     var hubConnection = new HubConnection(ConfigurationManager.AppSettings.Get("ServerAddressAndPort"));
     IHubProxy proxy = null;
     switch (hubName)
     {
         case "UserHub":
         {
             proxy = hubConnection.CreateHubProxy("UserHub");
             break;
         }
         case "MessageHub":
         {
             proxy = hubConnection.CreateHubProxy("MessageHub");
             break;
         }
         case "ConversationHub":
         {
             proxy = hubConnection.CreateHubProxy("ConversationHub");
             break;
         }
     }
     ServicePointManager.DefaultConnectionLimit = 20;
     await hubConnection.Start();
     return proxy;
 }
        //Data should be brought down from the SERVER, more specifically from the PLAYERLIST. Four slots, one for each of the four players.
        //If no data available, say N/A (Not Applicable)
        //If possible, display in order of score/health, so that pausing the game shows who's 'winning' or 'losing' at that time.

        public DisplayMenu(Texture2D bttnContinueSprite)
        {
            bttnContinue = new MenuButton(bttnContinueSprite, new Point(700, 570));
            HubConnection connection = new HubConnection("http://localhost:56859");
            proxy = connection.CreateHubProxy("UserInputHub");
            connection.Start().Wait();
        }
Example #33
0
        public async Task ConnectStatusStreamAsync()
        {
            if (_connectionConfig.ServerMode == "v1")
            {
                // older signalr client/server
                _legacyConnection = new Microsoft.AspNet.SignalR.Client.HubConnection(_statusHubUri);
                _legacyConnection.Credentials = System.Net.CredentialCache.DefaultCredentials;

                var hubProxy = _legacyConnection.CreateHubProxy("StatusHub");

                hubProxy.On<ManagedCertificate>(Providers.StatusHubMessages.SendManagedCertificateUpdateMsg, (u) => OnManagedCertificateUpdated?.Invoke(u));
                hubProxy.On<RequestProgressState>(Providers.StatusHubMessages.SendProgressStateMsg, (s) => OnRequestProgressStateUpdated?.Invoke(s));
                hubProxy.On<string, string>(Providers.StatusHubMessages.SendMsg, (a, b) => OnMessageFromService?.Invoke(a, b));

                _legacyConnection.Reconnecting += OnConnectionReconnecting;
                _legacyConnection.Reconnected += OnConnectionReconnected;
                _legacyConnection.Closed += OnConnectionClosed;

                await _legacyConnection.Start();

            }
            else
            {
                // newer signalr client/server

                // TODO: auth: https://docs.microsoft.com/en-us/aspnet/core/signalr/authn-and-authz?view=aspnetcore-3.1

                connection = new HubConnectionBuilder()
                .WithUrl(_statusHubUri)
                .WithAutomaticReconnect()
                .AddMessagePackProtocol()
                .Build();

                connection.Closed += async (error) =>
                {
                    await Task.Delay(new Random().Next(0, 5) * 1000);
                    await connection.StartAsync();
                };

                connection.On<RequestProgressState>(Providers.StatusHubMessages.SendProgressStateMsg, (s) =>
                {
                    OnRequestProgressStateUpdated?.Invoke(s);
                });

                connection.On<ManagedCertificate>(Providers.StatusHubMessages.SendManagedCertificateUpdateMsg, (u) =>
                {
                    OnManagedCertificateUpdated?.Invoke(u);
                });

                connection.On<string, string>(Providers.StatusHubMessages.SendMsg, (a, b) =>
                {
                    OnMessageFromService?.Invoke(a, b);
                });

                await connection.StartAsync();
            }
        }
Example #34
0
        public virtual void Dispose()
        {
            reconnect = false;

            Stop();

            hubConnection?.Dispose();
            hubConnection = null;
        }
Example #35
0
        private bool AuthenticateUser(string user, string password)
        {
            _Authenticated = false;
            if (_UsingWindowsAuth)
            {
                try
                {
                    using (var connection = new Microsoft.AspNet.SignalR.Client.HubConnection(RemoteDesktop_CSLibrary.Config.SignalRHubUrl))
                    {
                        connection.TransportConnectTimeout = new TimeSpan(0, 0, 4);
                        RemoteDesktop_CSLibrary.Config.SignalRHubUrl.Split('/').LastOrDefault();
                        IHubProxy stockTickerHubProxy = connection.CreateHubProxy(RemoteDesktop_CSLibrary.Config.SignalRHubName);
                        connection.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
                        connection.Error      += connection_Error;
                        connection.Start().Wait(RemoteDesktop_CSLibrary.Config.AuthenticationTimeout);
                        _Authenticated = true;
                        return(_Authenticated);
                    }
                }
                catch (Exception e)
                {
                    _Authenticated = false;
                }
            }
            else
            {
                var request = WebRequest.Create(RemoteDesktop_CSLibrary.Config.AuthenticationUrl) as HttpWebRequest;

                request.Method          = "POST";
                request.ContentType     = "application/x-www-form-urlencoded";
                request.CookieContainer = new CookieContainer();
                request.Timeout         = RemoteDesktop_CSLibrary.Config.AuthenticationTimeout;
                var    authCredentials = "UserName="******"&Password="******".ASPXAUTH"];
                    }
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e.Message);
                }
                _Authenticated = _AuthCookie != null;
            }
            return(_Authenticated);
        }
Example #36
0
 private void button1_Click(object sender, EventArgs e)
 {
     connection = new Microsoft.AspNet.SignalR.Client.HubConnection(ServerUri);
     //类名必须与服务端一致
     //myHub = connection.CreateHubProxy("BroadcastHub");
     rhub = connection.CreateHubProxy("myhub");
     connection.Start();//连接服务器
     label1.Text = "连接服务器成功!";
     //注册客户端方法名称"addMessage"与服务器端Send方法对应,对应的 callback方法 ReceiveMsg
     rhub.On <string, string>("addMessage", ReceiveMsg);
 }
Example #37
0
        public HubConnection(string url, string id, string endpointData, string hubName)
        {
            HubName = hubName;

            hubConnection = new Microsoft.AspNet.SignalR.Client.HubConnection(url);
            hubConnection.StateChanged += OnStateChanged;
            hubConnection.Credentials   = CredentialCache.DefaultCredentials;
            hubConnection.Headers.Add("id", id);
            hubConnection.Headers.Add("endpoint", endpointData);

            CreateProxy();
        }
Example #38
0
        async void IniSignalR(string serverUri)
        {
            connection = new Microsoft.AspNet.SignalR.Client.HubConnection(serverUri);
            //类名必须与服务端一致
            //myHub = connection.CreateHubProxy("BroadcastHub");
            rhub = connection.CreateHubProxy("MyHub");


            ////注册客户端方法名称"addMessage"与服务器端Send方法对应,对应的 callback方法 ReceiveMsg
            rhub.On("Register", Register);
            await connection.Start();//连接服务器
        }
Example #39
0
        public virtual void Dispose()
        {
            using (Trace.Log())
            {
                reconnect = false;

                //Stop();

                hubConnection.StateChanged -= OnStateChanged;
                hubConnection.Dispose();
                hubConnection = null;
            }
        }
Example #40
0
        public static void PreloadDLLS()
        {
            try
            {
                using (var connection = new Microsoft.AspNet.SignalR.Client.HubConnection(RemoteDesktop_CSLibrary.Config.SignalRHubUrl))
                {
                    connection.TransportConnectTimeout = new TimeSpan(0, 0, 4);
                    IHubProxy stockTickerHubProxy = connection.CreateHubProxy(RemoteDesktop_CSLibrary.Config.SignalRHubName);
                }
                var request = WebRequest.Create(RemoteDesktop_CSLibrary.Config.AuthenticationUrl) as HttpWebRequest;

                request.Method = "POST";
            }
            catch (Exception e)
            {
            }
        }
Example #41
0
        public HubConnection(string url, string id, string signalrUrl, string webUrl, string hubName)
        {
            using (Trace.Log())
            {
                HubName = hubName;

                Identifier = id;

                hubConnection = new Microsoft.AspNet.SignalR.Client.HubConnection(url);
                hubConnection.StateChanged += OnStateChanged;
                hubConnection.Credentials   = CredentialCache.DefaultCredentials;
                hubConnection.Headers.Add("id", id);
                hubConnection.Headers.Add("signalrUrl", signalrUrl);
                hubConnection.Headers.Add("webUrl", webUrl);

                CreateProxy();
            }
        }
Example #42
0
 private void Form1_Load(object sender, EventArgs e)
 {
     Connection         = new Microsoft.AspNet.SignalR.Client.HubConnection(ServerUrl);
     Connection.Closed += Connection_Closed;
     HubProxy           = Connection.CreateHubProxy("MyHub");
     HubProxy.On <string, string>("addMessage", RecvMsg);//接收实时信息
     Connection.Start().ContinueWith(task =>
     {
         if (!task.IsFaulted)
         {
             msgContent.AppendText(string.Format("与Signal服务器连接成功,服务器地址:{0}\r\n", ServerUrl));
         }
         else
         {
             msgContent.AppendText("与服务器连接失败,请确认服务器是否开启。\r\n");
         }
     }).Wait();
 }
Example #43
0
        private static void Main(string[] args)
        {
            var conn = new Microsoft.AspNet.SignalR.Client.HubConnection("http://localhost:55740/");
            var hub  = conn.CreateHubProxy("planHub");

            hub.On <int, int>("Updated", (plan, result) =>
            {
                Console.WriteLine("PLAN  :{0}", plan);
                Console.WriteLine("RESULT:{0}", result);
                Console.WriteLine("DIFF  :{0}", result - plan);
            });
            conn.Start().ContinueWith(t =>
            {
                if (args.Length == 2)
                {
                    hub.Invoke("Update", int.Parse(args[0]), int.Parse(args[1]));
                }
                else
                {
                    hub.Invoke("GetPlan");
                }
            });
            Console.ReadLine();
        }
Example #44
0
 /// <summary>
 ///     Ctor of HubProxy.
 /// </summary>
 /// <param name="hubConnection">HubConnection.</param>
 /// <param name="hubName">Name of the hub.</param>
 public HubProxy(HubConnection hubConnection, string hubName)
     : this(hubConnection.CreateHubProxy(hubName))
 {
 }
Example #45
0
        public async Task ConnectStatusStreamAsync()
        {
            if (_connectionConfig.ServerMode == "v1")
            {
                // older signalr client/server
                _legacyConnection             = new Microsoft.AspNet.SignalR.Client.HubConnection(_statusHubUri);
                _legacyConnection.Credentials = System.Net.CredentialCache.DefaultCredentials;

                var hubProxy = _legacyConnection.CreateHubProxy("StatusHub");

                hubProxy.On <ManagedCertificate>(Providers.StatusHubMessages.SendManagedCertificateUpdateMsg, (u) => OnManagedCertificateUpdated?.Invoke(u));
                hubProxy.On <RequestProgressState>(Providers.StatusHubMessages.SendProgressStateMsg, (s) => OnRequestProgressStateUpdated?.Invoke(s));
                hubProxy.On <string, string>(Providers.StatusHubMessages.SendMsg, (a, b) => OnMessageFromService?.Invoke(a, b));

                _legacyConnection.Reconnecting += OnConnectionReconnecting;
                _legacyConnection.Reconnected  += OnConnectionReconnected;
                _legacyConnection.Closed       += OnConnectionClosed;

                await _legacyConnection.Start();
            }
            else
            {
                // newer signalr client/server

                // TODO: auth: https://docs.microsoft.com/en-us/aspnet/core/signalr/authn-and-authz?view=aspnetcore-3.1

                connection = new HubConnectionBuilder()
                             .WithUrl(_statusHubUri, opts =>
                {
                    opts.HttpMessageHandlerFactory = (message) =>
                    {
                        if (message is System.Net.Http.HttpClientHandler clientHandler)
                        {
                            if (_connectionConfig.AllowUntrusted)
                            {
                                // allow invalid tls cert
                                clientHandler.ServerCertificateCustomValidationCallback +=
                                    (sender, certificate, chain, sslPolicyErrors) => { return(true); };
                            }
                        }
                        return(message);
                    };
                })
                             .WithAutomaticReconnect()
                             .AddMessagePackProtocol()
                             .Build();

                connection.Closed += async(error) =>
                {
                    await Task.Delay(new Random().Next(0, 5) * 1000);

                    await connection.StartAsync();
                };

                connection.On <RequestProgressState>(Providers.StatusHubMessages.SendProgressStateMsg, (s) =>
                {
                    OnRequestProgressStateUpdated?.Invoke(s);
                });

                connection.On <ManagedCertificate>(Providers.StatusHubMessages.SendManagedCertificateUpdateMsg, (u) =>
                {
                    OnManagedCertificateUpdated?.Invoke(u);
                });

                connection.On <string, string>(Providers.StatusHubMessages.SendMsg, (a, b) =>
                {
                    OnMessageFromService?.Invoke(a, b);
                });

                await connection.StartAsync();
            }
        }
Example #46
0
        public void Initialize(String pEndpoint)
        {
            _connection = new HubConnection(pEndpoint);
            _connection.Headers.Add("authtoken", "ThisIsACustomTokenToPreventSpamBecauseFuckIt");

            _connection.Received     += Connection_Received;
            _connection.StateChanged += delegate(StateChange obj){ OnPropertyChanged(nameof(ConnectionState)); NotifyLogMessageEvent($"state changed from {obj.OldState} to {obj.NewState}"); };
            _connection.Received     += delegate(String s) { NotifyLogMessageEvent(s); };
            _connection.Error        += delegate(Exception ex) { NotifyLogMessageEvent(ex.Message); };
            _connection.Reconnecting += delegate() { NotifyLogMessageEvent("reconnecting"); };
            _connection.Reconnected  += delegate { _hub.Invoke("Connect", _machineData); NotifyLogMessageEvent("reconnected"); };
            _connection.Closed       += delegate() {
                NotifyLogMessageEvent("closed... restarting...");
                Initialize(pEndpoint);
            };
            Connect();

            _pollTimer?.Dispose();
            _pollTimer = new Timer(delegate(object state)
            {
                if (IsWorking)
                {
                    return;
                }

                IsWorking = true;

                try
                {
                    var work = FetchWork();
                    if (work == null)
                    {
                        return;
                    }

                    //init client status
                    _clientStatus.IsWorking             = true;
                    _clientStatus.CurrentEpoch          = 0;
                    _clientStatus.LastEpochDuration     = "none";
                    _clientStatus.CurrentWorkParameters = work.Commands.First().Parameters;
                    SendStatusUpdate(_clientStatus);

                    //create log

                    //run process
                    NotifyLogMessageEvent("Create process.");
                    DateTime startTime = DateTime.UtcNow;
                    foreach (var command in work.Commands)
                    {
                        NotifyLogMessageEvent($"[DEBUG] Create process for: {command.FileName} {command.Arguments} {command.WorkDir}");
                        var startInfo = new ProcessStartInfo()
                        {
                            FileName               = command.FileName,
                            WorkingDirectory       = command.WorkDir,
                            Arguments              = command.Arguments,
                            RedirectStandardOutput = true,
                            RedirectStandardInput  = false,
                            RedirectStandardError  = true,
                            UseShellExecute        = false
                        };
                        using (var process = Process.Start(startInfo))
                        {
                            process.OutputDataReceived += (sender, args) => NotifyLogMessageEvent(args.Data);
                            process.ErrorDataReceived  += (sender, args) => NotifyLogMessageEvent(args.Data);
                            NotifyLogMessageEvent($"[DEBUG] Starting process for: {command.FileName} {command.Arguments} {command.WorkDir}");
                            process.BeginOutputReadLine();
                            process.BeginErrorReadLine();
                            process.WaitForExit();
                            NotifyLogMessageEvent($"[DEBUG] Finished process for: {command.FileName} {command.Arguments} {command.WorkDir}");
                        }
                    }
                    NotifyLogMessageEvent("Process finished.");

                    //get results
                    NotifyLogMessageEvent($"[DEBUG] Read target files");
                    List <ResultPackage.File> resultFiles = new List <ResultPackage.File>();
                    foreach (var pathlist in work.TargetFiles)
                    {
                        var path     = System.IO.Path.Combine(pathlist.ToArray());
                        var filename = System.IO.Path.GetFileName(path);
                        var bytes    = System.IO.File.ReadAllBytes(path);

                        resultFiles.Add(new ResultPackage.File()
                        {
                            FileData = bytes,
                            Filename = filename
                        });
                    }
                    SendResults(new ResultPackage()
                    {
                        WorkPackage       = work,
                        DurationTime      = DateTime.UtcNow - startTime,
                        ClientStatusAtEnd = _clientStatus,
                        ResultFiles       = resultFiles,
                        MachineData       = _machineData,
                        OutLog            = FlushLog(this.SavedLog)
                    });
                    NotifyLogMessageEvent($"[DEBUG] Finished reading file modelfile");
                }
                catch (Exception e)
                {
                    IsWorking = false;
                    _clientStatus.IsWorking = false;
                    SendStatusUpdate(_clientStatus);
                    NotifyLogMessageEvent(e.Message);
                }
                finally
                {
                    IsWorking = false;
                    _clientStatus.IsWorking = false;
                    SendStatusUpdate(_clientStatus);
                }
            }, null, 6000, 60000);
        }