Ejemplo n.º 1
0
 public JabbRClient(string url, IClientTransport transport)
 {
     _url = url;
     _connection = new HubConnection(url);
     _chat = _connection.CreateProxy("JabbR.Chat");
     _clientTransport = transport ?? new AutoTransport();
 }
Ejemplo n.º 2
0
        public Chat(HubConnection connection)
        {
            _chat = connection.CreateProxy("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);
                }
            });
        }
Ejemplo n.º 3
0
 public Bot(string url, string name, string password)
 {
     Name = name;
     _password = password;
     _connection = new HubConnection(url);
     _chat = _connection.CreateProxy("JabbR.Chat");
 }
        private async void Go()
        {
            var hubConnection = new HubConnection("http://localhost:1235/");
            var hub = hubConnection.CreateProxy("moveShape");
            
            hub.On<string, double, double>("shapeMoved", (cid, x, y) =>
                {
                    if (hubConnection.ConnectionId != cid)
                    {
                        Dispatcher.InvokeAsync(() =>
                            {
                                Canvas.SetLeft(Shape, (Body.ActualWidth - Shape.ActualWidth) * x);
                                Canvas.SetTop(Shape, (Body.ActualHeight - Shape.ActualHeight) * y);
                            });
                    }
                });

            hub.On<int>("clientCountChanged", count => Dispatcher.InvokeAsync(() => ClientCount.Text = count.ToString()));

            await hubConnection.Start();
            
            Shape.Draggable((left, top) =>
                {
                    hub.Invoke("MoveShape",
                        left / (Body.ActualWidth - Shape.ActualWidth),
                        top / (Body.ActualHeight - Shape.ActualHeight));
                });
        }
Ejemplo n.º 5
0
        public MainPage()
        {
            InitializeComponent();

            textBlockMessages.Dispatcher.BeginInvoke(new Action(() => textBlockMessages.Text = "This program, SignalRWp7, begins\n"));

            hubConnection = new HubConnection("http://localhost:49522/");

            hubConnection.Start().ContinueWith(task =>
            {
                if (task.IsFaulted)
                {
                    Console.WriteLine("Failed to start: {0}", task.Exception.GetBaseException());
                }
                else
                {
                    Console.WriteLine("Success! Connected with client connection id {0}", hubConnection.ConnectionId);
                    // Do more stuff here
                }
            });

            hubConnection.Received += data =>
            {
                HubBub deserializedHubBub = JsonConvert.DeserializeObject<HubBub>(data);
                var args0 = deserializedHubBub.Args[0];
                UpdateMessages(args0);
            };

            chatHub = hubConnection.CreateProxy("Chat");
        }
Ejemplo n.º 6
0
        static void StartClient()
        {
            var hub = new HubConnection("http://localhost:49899/");
            var proxy = hub.CreateProxy("LivePricingHub");

            proxy.On("TradeOccurred", d =>
            {
                Console.WriteLine("UPDATE: {0} - {1:C} ({2:N0})", d.ShortCode, d.LastTradePrice, d.TradeVolume);
            });

            hub.Start()
                .ContinueWith(t =>
                {
                    count++;

                    for (int x = 0; x < 20; x++)
                    {
                        var listenTask = proxy.Invoke<dynamic>("ListenForPriceChanges", string.Format("Share {0}", x));
                        listenTask.ContinueWith(priceTask =>
                            {
                                var price = priceTask.Result;

                            }, TaskContinuationOptions.OnlyOnRanToCompletion);
                    }

                    Console.WriteLine("{0} Connected", count);

                }, TaskContinuationOptions.OnlyOnRanToCompletion);
        }
Ejemplo n.º 7
0
 public DynamicHubProxyInterceptor(HubConnection connection, Type type)
 {
     _type = type;
     var name = type.Name.Substring(1);
     _proxy = connection.CreateProxy(name);
     _connection = connection;
     _genericInvokeMethod = _proxy.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Public).Where(m => m.Name == "Invoke" && m.ContainsGenericParameters).SingleOrDefault();
 }
Ejemplo n.º 8
0
 static void Main(string[] args)
 {
     var hubConnection = new HubConnection("http://localhost:8081/");
     var ddpStream = hubConnection.CreateProxy("DDPStream");
     ddpStream.On("flush", message => System.Console.WriteLine(message.prodName));
     hubConnection.Start().Wait();
     ddpStream.Invoke("Subscribe", "allproducts","product");
     System.Console.Read();
 }
Ejemplo n.º 9
0
        static void Main(string[] args)
        {
            var hubConnection = new HubConnection("http://localhost:40476/");

            RunDemoHub(hubConnection);

            RunStreamingSample();

            Console.ReadKey();
        }
Ejemplo n.º 10
0
        public StudentService(DataClassesDataContext context, HubConnection hubConn)
        {
            if (context == null)
            throw new ArgumentNullException("`context` cannot be null.");
              if (hubConn == null)
            throw new ArgumentNullException("`hubConn` cannot be null.");

              _context = context;
              _hubConn = hubConn;
        }
Ejemplo n.º 11
0
        static void Main(string[] args)
        {
            //輸入識別名稱

            Console.Write("Please input client name: ");

            string clientName = Console.ReadLine();

            //連線SignalR Hub

            var connection = new HubConnection("http://localhost:4112/");

            IHubProxy commHub = connection.CreateProxy("CommHub");

            //顯示Hub傳入的文字訊息

            commHub.On("ShowMessage", msg => Console.WriteLine(msg));

            //利用done旗標決定程式中止

            bool done = false;

            //當Hub要求執行Exit()時,將done設為true

            commHub.On("Exit", () => { done = true; });

            //建立連線,連線建立完成後向Hub註冊識別名稱

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

                if (!task.IsFaulted)

                    //連線成功時呼叫Server端方法register()

                    commHub.Invoke("register", clientName);

                else

                    done = true;

            });

            //維持程式執行迴圈

            while (!done)
            {

                Thread.Sleep(100);

            }

            //主動結束連線
            connection.Stop();
        }
Ejemplo n.º 12
0
        public TaskHub()
        {
            string signalrService = "http://andyjmay.com/Apps/TaskR";
              hubConnection = new HubConnection(signalrService);
              hubProxy = hubConnection.CreateProxy("TaskHub");

              hubProxy.On<IEnumerable<Task>>("GotTasksForUser", tasks => DispatcherHelper.UIDispatcher.BeginInvoke(() => Messenger.Default.Send(new GotTasksForUserEvent(tasks))));
              hubProxy.On<string>("GotLogMessage", message => DispatcherHelper.UIDispatcher.BeginInvoke(() => Messenger.Default.Send(new GotLogMessageEvent(message))));
              hubProxy.On<Task>("AddedTask", task => DispatcherHelper.UIDispatcher.BeginInvoke(() => Messenger.Default.Send(new AddedTaskEvent(task))));
              hubProxy.On<Task>("UpdatedTask", task => DispatcherHelper.UIDispatcher.BeginInvoke(() => Messenger.Default.Send(new UpdatedTaskEvent(task))));
              hubProxy.On<Task>("DeletedTask", task => DispatcherHelper.UIDispatcher.BeginInvoke(() => Messenger.Default.Send(new DeletedTaskEvent(task))));
              hubProxy.On<Exception>("HandleException", exception => DispatcherHelper.UIDispatcher.BeginInvoke(() => Messenger.Default.Send(new ExceptionEncounteredEvent(exception))));

              Messenger.Default.Register<LoginEvent>(this, (e) => {
            Login(e.Username);
              });

              Messenger.Default.Register<AddTaskEvent>(this, (e) => {
            AddTask(e.TaskToAdd);
              });

              Messenger.Default.Register<UpdateTaskEvent>(this, (e) => {
            UpdateTask(e.TaskToUpdate);
              });

              Messenger.Default.Register<DeleteTaskEvent>(this, (e) => {
            DeleteTask(e.TaskToDelete);
              });

              hubConnection.Start().ContinueWith(task => {
            if (task.IsFaulted) {
              DispatcherHelper.UIDispatcher.BeginInvoke(new Action(() => Messenger.Default.Send(new Events.ExceptionEncounteredEvent(task.Exception))));
              return;
            }
            if (task.IsCompleted) {
              DispatcherHelper.UIDispatcher.BeginInvoke(new Action(() => {
            Messenger.Default.Send(new ConnectedToHubEvent());
            //Messenger.Default.Send(new LoginEvent("andyjmay"));
            //var loginWindow = new LoginView();
            //loginWindow.Closed += (sender, ev) =>
            //{
            //    LoginView loginView = (LoginView)sender;
            //    bool? result = loginView.DialogResult;
            //    if (result.HasValue && result.Value == true)
            //    {
            //        Messenger.Default.Send(new LoginEvent(loginView.Username));
            //    }
            //};
            //loginWindow.ShowDialog();
              }));
            }
              });
        }
Ejemplo n.º 13
0
 public TorshifySongPlayerClient(Uri serverUri)
 {
     _connection = new HubConnection(serverUri.AbsoluteUri);
     _proxy = _connection.CreateProxy("TorshifyHub");
     _proxy.On<ValueProgressEventArgs<int>>("Progress", OnProgress);
     _proxy.On<ValueProgressEventArgs<int>>("Buffering", OnBuffering);
     _proxy.On<ValueChangedEventArgs<float>>("VolumeChanged", OnVolumeChanged);
     _proxy.On<ValueChangedEventArgs<bool>>("IsMutedChanged", OnIsMutedChanged);
     _proxy.On<ValueChangedEventArgs<bool>>("IsPlayingChanged", OnIsPlayingChanged);
     _proxy.On<ValueChangedEventArgs<Song>>("CurrentSongChanged", OnCurrentSongChanged);
     _proxy.On<SongEventArgs>("CurrentSongCompleted", OnCurrentSongCompleted);
 }
Ejemplo n.º 14
0
        public void Stop()
        {
            //for some reason when the process is stoping all the private instances in the object are missing
            //need to create specificaly for shutdown
            _hubConnection = new HubConnection(url);
            _hubConnection.ConnectionId = bus.InputAddress.Queue;
            _monitor = _hubConnection.CreateProxy("MonitorHub");
            _hubConnection.Start().Wait();
            _monitor.Invoke("Deregister", new { Server = bus.InputAddress.Machine, Endpoint = bus.InputAddress.Queue });

            _hubConnection.Stop();
        }
Ejemplo n.º 15
0
 static void Main(string[] args)
 {
     var connection = new HubConnection("http://localhost:9616/");
     SignalRConsole.SignalR.MessengerHub.Message message = new SignalR.MessengerHub.Message();
     message.Content = "Moo";
     message.Duration = 500;
     message.Title = "Hello Title";
     var myHub = connection.CreateProxy("messenger");
     connection.Start().Wait();
     Object[] myData = { (Object)message, "sourcing" };
     myHub.Invoke("broadCastMessage", myData);
 }
Ejemplo n.º 16
0
        public virtual void Init(TextWriter log)
        {
            this.log = log;
            secret = ConfigurationManager.AppSettings["TwitterCustomerSecret"];

            while (streamingHubConnectAttempts++ < 3)
            {
                if (streamingHubConnectAttempts > 1) System.Threading.Thread.Sleep(5000);

                log.WriteLine("{0}: Attempting To Connect To PushURL '{1}' (Attempt: {2})", DateTime.Now, ConfigurationManager.AppSettings["PushURL"], streamingHubConnectAttempts);
                hubConnection = (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["PushURL"])) ? new HubConnection(ConfigurationManager.AppSettings["PushURL"]) : null;

                if (hubConnection != null)
                {
                    try
                    {
                        streamingHub = hubConnection.CreateProxy("streamingHub");
                        hubConnection.StateChanged += new Action<SignalR.Client.StateChange>(sc =>
                        {
                            if (sc.NewState == SignalR.Client.ConnectionState.Connected)
                            {
                                log.WriteLine("{0}: Push Connection Established", DateTime.Now);
                                lock (queue_push_lock)
                                {
                                    if (queue_push.Count > 0)
                                    {
                                        log.WriteLine("{0}: Pushing {1} Tweets to Web Application", DateTime.Now, queue_push.Count());
                                        streamingHub.Invoke("Send", new StreamItem() { Secret = secret, Data = queue_push }).Wait();
                                        queue_push.Clear();
                                    }
                                }
                            }
                            else if (sc.NewState == SignalR.Client.ConnectionState.Disconnected)
                                log.WriteLine("{0}: Push Connection Lost", DateTime.Now);
                            else if (sc.NewState == SignalR.Client.ConnectionState.Reconnecting)
                                log.WriteLine("{0}: Reestablishing Push Connection", DateTime.Now);
                            else if (sc.NewState == SignalR.Client.ConnectionState.Connecting)
                                log.WriteLine("{0}: Establishing Push Connection", DateTime.Now);

                        });
                        var startHubTask = hubConnection.Start();
                        startHubTask.Wait();
                        if (!startHubTask.IsFaulted) break;
                    }
                    catch (Exception ex)
                    {
                        hubConnection = null;
                        log.WriteLine("{0}: Error: {1}", DateTime.Now, ex.ToString());
                    }
                }
            }
        }
Ejemplo n.º 17
0
        public ActionResult Broadcast()
        {
            var conn = new HubConnection(Queue_Demo.Settings.hubUrl);

            var hub = conn.CreateProxy("queue");

            var waitTime = "1000";

            conn.Start().Wait();

            hub.Invoke("ReportAverageWait", new object[] { waitTime });

            return new EmptyResult();
        }
        static void Main(string[] args)
        {
            // AWS: Get instance public address
            string myId = "localhost";
            try
            {
                myId = Encoding.ASCII.GetString(new WebClient().DownloadData("http://169.254.169.254/latest/meta-data/public-hostname"));
            }
            catch
            {
            }

            // AWS SQS Client
            var sqsClient = new AmazonSQSClient();

            while (true)
            {
                // Get the next message
                ReceiveMessageRequest request = new ReceiveMessageRequest()
                    .WithQueueUrl("https://queue.amazonaws.com/*****/codeCampDemo")
                    .WithMaxNumberOfMessages(1);
                var response = sqsClient.ReceiveMessage(request);

                foreach (var retrievedMessage in response.ReceiveMessageResult.Message)
                {
                    var messageJson = JsonValue.Parse(retrievedMessage.Body);

                    var message = messageJson["message"].ReadAs<string>();

                    Console.WriteLine(message);

                    message = "Echo: " + message;

                    string address = string.Format("http://{0}", messageJson["sender"].ReadAs<string>());
                    var connection = new HubConnection(address);
                    connection.Start().Wait();

                    IHubProxy pongHub = connection.CreateProxy("MvcWebRole1.Hubs.EchoHub");
                    pongHub.Invoke("DoUpdateMessage", message, myId).Wait();

                    //Process the message and then delete the message
                    DeleteMessageRequest deleteRequest = new DeleteMessageRequest()
                        .WithQueueUrl("https://queue.amazonaws.com/******/codeCampDemo")
                        .WithReceiptHandle(retrievedMessage.ReceiptHandle);
                    sqsClient.DeleteMessage(deleteRequest);
                }

                Thread.Sleep(1000);
            }
        }
Ejemplo n.º 19
0
        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();
        }
Ejemplo n.º 20
0
        private void StartHubConnection()
        {
            hubConnection = new HubConnection("http://openpanel.apphb.com");
            var topicHub = hubConnection.CreateProxy("topicHub");

            topicHub.On<int, int, int>("voteUpdated", (answerId, topicId, vote) =>
            {
                if (Topic.Id == topicId)
                {
                    InvokeOnMainThread(() => { UpdateVoteCount(answerId, vote); });
                }
            });

            hubConnection.Start();
        }
 static void startConnection(HubConnection connection)
 {
     connection.Start().ContinueWith(
         t =>
         {
             if (t.IsFaulted)
             {
                 Console.WriteLine("Error opening connection");
             }
             else
             {
                 Console.WriteLine("Connected");
             }
         }).Wait();
 }
Ejemplo n.º 22
0
        static void Main(string[] args)
        {
            var connection = new HubConnection("http://localhost/WebApplication2/");

            var hub = connection.CreateProxy("Chat");

            hub.On<string>("AddMessage", Console.WriteLine);

            connection.Start().ContinueWith(t =>
                {
                    hub.Invoke("Send", "Hello there from command line");
                });

            Console.ReadLine();
        }
Ejemplo n.º 23
0
        public MainWindow()
        {
            InitializeComponent();

            chatItems = new ObservableCollection<dynamic>();
            ChatResults.ItemsSource = chatItems;

            cn = new HubConnection("http://localhost:5687/");
            proxy = cn.CreateProxy("Chat");

            proxy.On("AddMessage", message => 
                Dispatcher.Invoke(new Action(() => chatItems.Add(message))));

            cn.Start();
        }
        public void Start()
        {
            string url = "http://localhost:8999/";

            var connection = new HubConnection(url);

            IHubProxy serverHub = connection.CreateProxy(typeof (ServerHub).GetHubName());

            serverHub.On("foo", () => Console.WriteLine("notified!"));

            serverHub.On("foo", s => Console.WriteLine(s));

            startConnection(connection);

            serverHub.Invoke("SendMessage", "hello from Console Client").Wait();
        }
Ejemplo n.º 25
0
        static void Main(string[] args)
        {
            var hubConn = new HubConnection("http://localhost:7458/");
            hubConn.Credentials = CredentialCache.DefaultNetworkCredentials;

            var msg = new NiCris.Web.ConsoleTester.Models.Message();
            msg.Content = "Moo";
            msg.Duration = 500;
            msg.Title = "Hello Title";

            var hub = hubConn.CreateProxy("messenger");
            hubConn.Start().Wait();
            
            Object[] myData = { (Object)msg, "sourcing" };
            hub.Invoke("broadCastMessage", myData);
        }
Ejemplo n.º 26
0
 /// <summary>
 /// Logs into the MessengR service using forms auth and retrives an auth cookie.
 /// </summary>
 public static Task<AuthenticationResult> LoginAsync(string url, string userName, string password)
 {
     HubConnection connection = new HubConnection(url) { CookieContainer = new CookieContainer() }; ;
     TaskHub taskHub = new TaskHub(connection);
     var tcs = new TaskCompletionSource<AuthenticationResult>();
     connection.Start().ContinueWith(task =>
      {
       taskHub.Logon(userName, password).ContinueWith(logon => 
           taskHub.LogonStatus += logonStatus => tcs.SetResult(new AuthenticationResult
                                                                   {
                                                                       Status = logonStatus.Status
                                                                   }));
      });
     
     return tcs.Task;
 }
Ejemplo n.º 27
-1
        public override void Run()
        {
            var client = new TwilioRestClient(Queue_Demo.Settings.accountSid, Queue_Demo.Settings.authToken);

            var queue = client.ListQueues().Queues.Where(q => q.FriendlyName == "Demo Queue").FirstOrDefault();

            if (queue!=null)
            {
                var queueSid = queue.Sid;

                var conn = new HubConnection(Queue_Demo.Settings.hubUrl);
                var hub = conn.CreateProxy("Queue");

                conn.Start();

                while (true)
                {
                    Thread.Sleep(10000);

                    var waitTime = client.GetQueue(queueSid).AverageWaitTime;

                    Debug.WriteLine(waitTime);

                    hub.Invoke("ReportAverageWait", new object[] { waitTime });
                }
            }
        }
Ejemplo n.º 28
-1
        private static void RunDemoHub(HubConnection hubConnection)
        {
            var demo = hubConnection.CreateProxy("demo");

            hubConnection.StateChanged += change =>
            {
                Console.WriteLine(change.OldState + " => " + change.NewState);
            };

            demo.On<int>("invoke", i =>
            {
                int n = demo.GetValue<int>("index");
                Console.WriteLine("{0} client state index -> {1}", i, n);
            });

            hubConnection.Start().Wait();

            demo.Invoke("multipleCalls").ContinueWith(task =>
            {
                Console.WriteLine(task.Exception);

            }, TaskContinuationOptions.OnlyOnFaulted);

            Task.Factory.StartNew(() =>
            {
                Thread.Sleep(7000);
                hubConnection.Stop();
            });
        }
Ejemplo n.º 29
-1
        public ConnectionManager(Dispatcher dispatcher)
        {
            _dispatcher = dispatcher;
#pragma warning disable 168
            const string localUrl = "http://localhost:20449/";
            const string remoteUrl = "http://192.168.10.42:8082/";
#pragma warning restore 168
            var hub = new HubConnection(remoteUrl);


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

            hub.Start().ContinueWith(delegate
                                         {
                                             if (Started != null)
                                                 _dispatcher.BeginInvoke(() => Started(this, new EventArgs()));
                                         }
                );
        }
Ejemplo n.º 30
-1
        public static void Process()
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("QueueConnectionString"));
            CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
            CloudQueue queue = queueClient.GetQueueReference("buy-queue");
            queue.CreateIfNotExist();

            CloudQueueMessage retrievedMessage = queue.GetMessage();

            if (retrievedMessage != null)
            {
                var item = JObject.Parse(retrievedMessage.AsString);

                Trace.WriteLine("Ordered: " + item["Name"], "Information");

                var message = "Processed: " + item["Name"];
                var instance = RoleEnvironment.CurrentRoleInstance.Role.Instances[0].Id;

                var connection = new HubConnection("http://" + item["Address"] + "/");
                connection.Start().ContinueWith(t =>
                    {
                        var processHub = connection.CreateProxy("MessagingHub");

                        processHub.Invoke("Processed", message, instance);
                    });

                queue.DeleteMessage(retrievedMessage);
            }
        }