예제 #1
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;
                  }
              });
        }
예제 #2
0
 public async Task SendAsync(string message)
 {
     if (IsConnected)
     {
         await eventsHubProxy?.Invoke("Send", accountId, message);
     }
 }
예제 #3
0
        private static void executeCommand(string address, string command,IHubProxy chat)
        {
            Console.WriteLine(address + " " + command);

            var result = x10Service.SendX10Command(command, address);
            if (result.Success)
            {
                chat.Invoke("DeviceStateChanged", address, command);
            }
            else
            {
                chat.Invoke("DeviceStateChanged", address, command=="on"?"off":"on");
                Logger.Log(result.Error);
            }
        }
예제 #4
0
파일: CommonRH.cs 프로젝트: gmahota/CRM_MIT
        public CommonRH(string url,string serverName)
        {
            var querystringData = new Dictionary<string, string>();
            querystringData.Add("name", serverName);

            hubConnection = new HubConnection(url,querystringData);

            rhHubProxy = hubConnection.CreateHubProxy("rhHub");
            

            rhHubProxy.On<int,string,string,string>("daListaEmpresa", (tipoPlataforma, codUtilizador, password,categoria) =>
                daListaEmpresas(tipoPlataforma, codUtilizador, password, categoria)
             );
            

            hubConnection.Start().Wait();
            Console.WriteLine("transport.Name={0}", hubConnection.Transport.Name);
            rhHubProxy.Invoke("message", "ola");
            //hubConnection.TraceWriter.WriteLine("transport.Name={0}", hubConnection.Transport.Name);

            //hubConnection.TraceWriter.WriteLine("Invoking long running hub method with progress...");
            //var result = await hubProxy.Invoke<string, int>("ReportProgress",
            //    percent => hubConnection.TraceWriter.WriteLine("{0}% complete", percent),
            //    /* jobName */ "Long running job");
            //hubConnection.TraceWriter.WriteLine("{0}", result);

            //await hubProxy.Invoke("multipleCalls");
        }
예제 #5
0
        public async void Notify(ISubcriber subcriber, BaseNotifierData data)
        {
            var signalrSubcriber = subcriber as SignalRSubcriber;
            var signalrData = data as MessageNotifierData;

            if (signalrSubcriber == null || signalrData == null)
                throw new AntelopeInvalidParameter();

            try
            {
                _connection = new HubConnection(signalrSubcriber.Url);

                _proxy = _connection.CreateHubProxy(HubName());

                _connection.Closed += OnConnectionClosed;

                await _connection.Start();
            }
            catch (HttpRequestException)
            {
                _logger.Info("Can't connect to {0}", signalrSubcriber.Url);
            }

            await _proxy.Invoke(HubMethod(), Formatter.Format(signalrData.Content));           
        }
        static void Main(string[] args)
        {
            Console.Write("Enter your Name: ");
            name = Console.ReadLine();

            HubConnection connection = new HubConnection("http://localhost:51734");
            proxy = connection.CreateHubProxy("ChatHub");

            connection.Received += Connection_Received;

            Action<string, string> SendMessageRecieved = recieved_a_message;

            proxy.On("broadcastMessage", SendMessageRecieved);

            Console.WriteLine("Waiting for connection");
            connection.Start().Wait();
            Console.WriteLine("You can send messages now.");

            connection.StateChanged += Connection_StateChanged;

            string input;
            while ((input = Console.ReadLine()) != null)
            {
                proxy.Invoke("Send", new object[] { name, input });
            }
        }
예제 #7
0
        private async void Init()
        {
            hubConnection = new HubConnection("http://localhost:5225");
            proxy = hubConnection.CreateHubProxy("MyHub");
            await hubConnection.Start();

            proxy.On<string>("executeCommand", (data) =>
            {
                Debug.WriteLine(data);
               // var message = Newtonsoft.Json.JsonConvert.DeserializeObject<Message>(data.ToString());
            });

            qmhubConnection = new HubConnection("http://quantifymewebhub.azurewebsites.net/");
            qmproxy = qmhubConnection.CreateHubProxy("QuantifyMeHub");
            await qmhubConnection.Start();

            qmproxy.On<string,string>("send", (name, data) =>
            {
                Debug.WriteLine(data);
                var message = new Message { Source = "RemoteUWP", Action = "UpdateData", Value = data };

                proxy.Invoke("Send", Newtonsoft.Json.JsonConvert.SerializeObject(message));

            });
        }
예제 #8
0
 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");
 }
예제 #9
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}");
            }
        }
예제 #10
0
        public GameplayScene(GraphicsDevice graphicsDevice)
            : base(graphicsDevice)
        {
            starfield = new Starfield(worldWidth, worldHeight, worldDepth);
            grid = new Grid(worldWidth, worldHeight);
            ShipManager = new ShipManager();
            BulletManager = new BulletManager();
            GameStateManager = new GameStateManager();

            AddActor(ShipManager);
            AddActor(BulletManager);
            AddActor(starfield);
            AddActor(grid);

            #if DEBUG
            hubConnection = new HubConnection("http://localhost:29058");
            #else
            hubConnection = new HubConnection("http://vectorarena.cloudapp.net");
            #endif
            hubProxy = hubConnection.CreateHubProxy("gameHub");
            hubProxy.On("Sync", data => Sync(data));
            hubConnection.Start().ContinueWith(startTask =>
            {
                hubProxy.Invoke<int>("AddPlayer").ContinueWith(invokeTask =>
                {
                    ShipManager.InitializePlayerShip(invokeTask.Result, hubProxy);
                    Camera.TargetObject = ShipManager.PlayerShip;
                    Camera.Position = new Vector3(ShipManager.PlayerShip.Position.X, ShipManager.PlayerShip.Position.Y, 500.0f);
                });
            });
        }
예제 #11
0
        private static void Enviar(IHubProxy _hub, string nome)
        {
            var mensagem = Console.ReadLine();
            _hub.Invoke("Send", nome, mensagem).Wait();

            Enviar(_hub, nome);
        }
        private async Task<ApiResultBase> StartRealtimeConnection(ConnectExtruderModel connectExtruderModel)
        {
            try
            {
                _connection = new HubConnection(SOS_URL);
                _proxy = _connection.CreateHubProxy("SosHub");

                _proxy.On<int?, TimeSpan?>("setLights", OnSetLightsEventReceived);
                _proxy.On<int?, TimeSpan?>("setAudio", OnSetAudioEventReceived);
                _proxy.On<ModalDialogEventArgs>("modalDialog", OnModalDialogEventReceived);
                _proxy.On("forceDisconnect", OnForceDisconnect);
                _proxy.On<TrayIcon>("setTrayIcon", OnSetTrayIcon);
                _proxy.On<TrayNotifyEventArgs>("trayNotify", OnTrayNotify);
                _connection.Error += ConnectionOnError;
                _connection.StateChanged += ConnectionOnStateChanged;
                _connection.Closed += ConnectionOnClosed;
                await _connection.Start();
                var result = await _proxy.Invoke<ApiResultBase>("connectExtruder", connectExtruderModel);
                if (!result.Success)
                {
                    _connection.Stop();
                }
                return result;
            }
            catch (Exception ex)
            {
                _log.Error("Unable to start realtime connection to SoS Online", ex);
                return new ApiResultBase {Success = false, ErrorMessage = ex.Message};
            }
        }
예제 #13
0
 private async void SendMessage(string command, double state)
 {
     try
     {
         await hub?.Invoke("newUpdate",
                           new object[] { command, state });
     }
     catch { }
 }
예제 #14
0
        private async Task SetupSignalRConnection()
        {
            _connection = new HubConnection("http://pbclone.azurewebsites.net/");
            _connection.StateChanged += ConnectionOnStateChanged;
            _mainHub = _connection.CreateHubProxy("imghub");

            await _connection.Start();

            _mainHub.Invoke("Create", _guid);
        }
예제 #15
0
 private static void Invoke(IHubProxy proxy, string method, string username) {
     Console.WriteLine("\nCalling server method " + method + " as " + username);
     try {
         proxy.Invoke(method, username + " invoked " + method + "() from console!").Wait();
     } catch (AggregateException ex) {
         foreach (var innerException in ex.InnerExceptions) {
             Console.WriteLine("    * " + innerException.Message);
         }
     }
 }
예제 #16
0
파일: SAGSignalR.cs 프로젝트: ohadmanor/TDS
        public static async Task SaveUserMaps(IHubProxy HubProxy, UserMaps usrMaps)
        {
            try
            {
                await HubProxy.Invoke<UserMaps>("SaveUserMaps", usrMaps);
            }
            catch (Exception ex)
            {
            }

        }
예제 #17
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");
 }
        private static async Task SendCompleteNotification(Message message, string uri)
        {
            var hubConnection = new HubConnection(url);
            hub = hubConnection.CreateHubProxy("GifServerHub");
            await hubConnection.Start();

            Console.WriteLine("Invoked  GifGenerationCompleted with URL: {0}", uri);
            await hub.Invoke("GifGenerationCompleted", message.HubId, uri);

            hubConnection.Stop();
        }
예제 #19
0
        static void Main(string[] args)
        {
            Console.Write("Enter name: ");
            Name = Console.ReadLine();

            HubConnection connection = new HubConnection("http://localhost:4039");
            proxy = connection.CreateHubProxy("ChatHub");

            connection.StateChanged += Connection_StateChanged;
            connection.Received += Connection_Received;
            Action<string, string> SendMessageRecieved = recieved_a_message;
            proxy.On("broadcastMessage", SendMessageRecieved);

            Action<int, int> IntsReceived = received_ints;
            proxy.On("broadcastScores", IntsReceived);

            connection.Start().Wait();

            Running = true;

            while (Running)
            {
                while ((Input = Console.ReadLine()) != null)
                {
                    try
                    {
                        int a, b;
                        a = Convert.ToInt32(Input);
                        Console.Write(" + ");
                        b = Convert.ToInt32(Console.ReadLine());
                        proxy.Invoke("SendInts", new object[] { a, b });
                    }
                    catch (Exception)
                    {

                    }
                    proxy.Invoke("Send", new object[] { Name, Input });
                }

            }
        }
        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
        }
예제 #21
0
파일: SAGSignalR.cs 프로젝트: ohadmanor/TDS
 public static async Task<IEnumerable<GeneralActivityDTO>> GetAllActivites(IHubProxy HubProxy)
 {
     try
     {
         IEnumerable<GeneralActivityDTO> activities = await HubProxy.Invoke<IEnumerable<GeneralActivityDTO>>("GetAllActivites");
         return activities;
     }
     catch (Exception ex)
     {
     }
     return null;
 }
예제 #22
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();
        }
예제 #23
0
        public async static void Connect()
        {
            var connection = new HubConnection("http://pbclone.azurewebsites.net/");
            //var connection = new HubConnection("http://localhost:4341/");
            _mainHub = connection.CreateHubProxy("imghub");

            await connection.Start().ContinueWith(_ =>
                                                {
                                                    _mainHub.Invoke("Create", "test");
                                                    //_mainHub.Invoke("SendMsg", "test ok");
                                                    //_mainHub.Subscribe("receiveMsg").Data += tokens => Console.WriteLine(tokens[0]);
                                                    _mainHub.Subscribe("ReceiveImage").Data += tokens =>
                                                                                                   {
                                                                                                       byte[] convertedFromBase64 = Convert.FromBase64String(tokens[0].ToString());

                                                                                                       Console.WriteLine
                                                                                                           (convertedFromBase64.Length);
                                                                                                   };
                                                    _mainHub.Invoke("ShareImage", new object[] { new byte[] { 1, 2 }, "test" });
                                                });
        }
        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;
            }
        }
예제 #25
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());
                    }
                }
            }
        }
예제 #26
0
파일: SAGSignalR.cs 프로젝트: ohadmanor/TDS
        public static async Task<UserParameters> GetUserParameters(IHubProxy HubProxy, string userName)
        {
            try
            {
                UserParameters Parameters = await HubProxy.Invoke<UserParameters>("GetUserParameters", userName);
                return Parameters;
            }
            catch (Exception ex)
            {
            }

            return null;
        }
예제 #27
0
파일: SAGSignalR.cs 프로젝트: ohadmanor/TDS
        //IEnumerable<GeneralActivityDTO>

        public static async Task<IEnumerable<GeneralActivityDTO>> GetActivitesByAtomName(IHubProxy HubProxy, string AtomName)
        {
            try
            {
                IEnumerable<GeneralActivityDTO> Activites = await HubProxy.Invoke<IEnumerable<GeneralActivityDTO>>("GetActivitesByAtomName", AtomName);
                return Activites;
            }
            catch (Exception ex)
            {
            }

            return null;
        }
예제 #28
0
파일: SAGSignalR.cs 프로젝트: ohadmanor/TDS
        public static async Task<UserMaps> GetUserMaps(IHubProxy HubProxy, string userName)
        {
            try
            {
                UserMaps maps = await HubProxy.Invoke<UserMaps>("GetUserMaps", userName);
                return maps;
            }
            catch (Exception ex)
            {
            }

            return null;
        }
        static void Main(string[] args)
        {
            HubConnection connection = new HubConnection("http://localhost:56859");
            proxy = connection.CreateHubProxy("ChatHub");

            connection.Received += Connection_Received;

            Action<string> SendMessagerecieved = recieved_a_message;
            proxy.On("BroadcastMessage", SendMessagerecieved);

            connection.Start().Wait();

            connection.StateChanged += Connection_StateChanged;

            proxy.Invoke("CountUsers", new object[] {  });

            string input;
            while ((input = Console.ReadLine()) != null)
            {
                proxy.Invoke("Send", new object[] { input });
            }
        }
예제 #30
0
        public WebClient(string url, string roomId, string username)
        {
            _url = url;
            _roomId = roomId;
            _username = username;
            _hubConnection = new HubConnection(url);

            HubProxy = _hubConnection.CreateHubProxy("RoomHub");

            _hubConnection.Start().Wait();

            HubProxy.Invoke("joinRoom", _roomId);
        }
예제 #31
0
        private async void Init()
        {
            _connection = new HubConnection("http://localhost:54506");
            _hub = _connection.CreateHubProxy("chatty");
            _hub.Subscribe("spoke").Data += tokens =>
                                                {
                                                    var name = tokens[0].ToString();
                                                    var message = tokens[1].ToString();
                                                    AddMessage(name, message);
                                                };

            await _connection.Start();
            await _hub.Invoke("setName", "Win8Tomas");
        }
예제 #32
0
        public MainPage()
        {
            hub = new HubConnection("http://localhost:13443");
            proxy = hub.CreateHubProxy("MyHub");
            proxy.On<string>("ServerNotified", (message) =>
            {
                System.Diagnostics.Debug.WriteLine(message);
            });

            hub.Start().Wait();

            proxy.Invoke("NotifyServer");
            this.InitializeComponent();
        }
예제 #33
0
        public async Task <UploadDataResponse> UploadData(UploadDataRequest request)
        {
            try
            {
                if (_hubConnection?.State != ConnectionState.Connected)
                {
                    return(new UploadDataResponse());
                }

                var response = await _hubProxy?.Invoke <UploadDataResponse>("UploadData", request);

                return(response);
            }
            catch (Exception e)
            {
                Logger.Exception(e);
                return(new UploadDataResponse());
            }
        }
예제 #34
0
        private void BeginNewConnection(string uri, string hubName)
        {
            try
            {
                var connection = new HubConnection(uri);
                connection.Error += (ex) =>
                {
                    NLog.Common.InternalLogger.Error(ex, "SignalR - Connection Failure. Uri={0}, HubName={1}", uri, hubName);
                };

                _proxy      = connection.CreateHubProxy(hubName);
                _connection = connection;
                StartExistingConnection(uri, hubName);
                _proxy?.Invoke("Notify", _connection.ConnectionId);
            }
            catch (Exception ex)
            {
                NLog.Common.InternalLogger.Error(ex, "SignalR - Create Connection Failure. Uri={0}, HubName={1}", uri, hubName);
                _proxy = null;
                throw;
            }
        }
예제 #35
0
파일: Chat.cs 프로젝트: tofutim/MessengR
 public Task<IEnumerable<User>> GetUsers()
 {
     return _chat.Invoke<IEnumerable<User>>("GetUsers");
 }
예제 #36
0
 public static async void sendMessage(IHubProxy h, string message, int tableId)
 {
     await h.Invoke("chat", message, tableId);
 }
예제 #37
0
        static void Main_(string[] args)
        {
            Console.WriteLine("Hello world from Console Client!");

            var url           = @"http://*****:*****@"stockTicker"; //"StockTickerHub"
            IHubProxy stockTickerHubProxy = hubConnection.CreateHubProxy(hubName);

            stockTickerHubProxy.On <Stock>("UpdateStockPrice", stock => Console.WriteLine("Stock update for {0} new price {1}", stock.Symbol, stock.Price));



            //QueryString can be used to pass information
            // between client vs. server: https://www.asp.net/signalr/overview/guide-to-the-api/hubs-api-guide-net-client

            //Specify header into connection
            hubConnection.Headers.Add("key", "value");

            //Client certificate can be added like this
            //hubConnection.AddClientCertificate()

            hubConnection.Start().Wait();

            //Types of transports - can specify in the Connection.Start method:
            // + LongPollingTransport
            // + ServerSentEventsTransport
            // + WebSocketTransport
            // + AutoTransport
            // + ForeverFrame - can only be used by the browser


            //Handle connection life time events:
            // + Received
            // + ConnectionSlow
            // + Reconnection
            // + Reconnected
            // + StateChanged
            // + Closed
            hubConnection.ConnectionSlow += () => Console.WriteLine("Connection problems.");

            //Handle an error raised by SignalR server
            hubConnection.Error += ex => Console.WriteLine("SignalR error: {0}", ex.Message);


            // ==============================
            // Enable client side logging
            // ==============================
            hubConnection.TraceLevel  = TraceLevels.All;
            hubConnection.TraceWriter = Console.Out;



            // ==============================
            // Handle error from server side method invocation
            // ==============================
            try
            {
                IEnumerable <Stock> allStocks = stockTickerHubProxy.Invoke <IEnumerable <Stock> >("GetAllStocks").Result;
                foreach (Stock stock in allStocks)
                {
                    Console.WriteLine("Symbol: {0} price: {1}", stock.Symbol, stock.Price);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error invoking GetAllStocks: {0}", ex.Message);
            }



            // ==============================
            // Call some methods on the server
            // ==============================

            //Call a method on the server - with server returning nothing
            stockTickerHubProxy.Invoke("JoinGroup", "SomeRandomGroup");

            //Call a method on the server - with server return some value
            var stocks = stockTickerHubProxy.Invoke <IEnumerable <Stock> >("AddStock", new Stock()
            {
                Symbol = "XYZ"
            }).Result;


            // ==============================
            // Some local methods that the server can call
            // ==============================

            // Method without params: Notify
            stockTickerHubProxy.On("Notify", () => Console.WriteLine("Notified!"));

            // With some params - string typing: UpdateStockPrice
            stockTickerHubProxy.On <Stock>("UpdateStockPrice", stock =>
                                           Console.WriteLine("Symbol {0} Price {1}", stock.Symbol, stock.Price)
                                           );

            // With some params - dynamic typing: UpdateStockPrice
            stockTickerHubProxy.On("UpdateStockPrice", stock =>
                                   Console.WriteLine("Symbol {0} Price {1}", stock.Symbol, stock.Price)
                                   );

            Console.ReadLine();
        }
예제 #38
0
 public async Task SendTransform(TransformModel transformModel)
 {
     await _hubProxy.Invoke(SendTransformMethodName, transformModel);
 }
 public async Task SignIn(string openId)
 {
     await _hubProxy.Invoke("SignIn", openId);
 }
예제 #40
0
        private void Timer_Tik(object sender, object e)
        {
            if (_timeMax > 0)
            {
                visible = "Collapsed";
                NotifyPropertyChanged("Visible");
                if (_timeMax % 10 == 0) //si es divisible entre 10 (o sea es 60, 50, 40, 30, 20, 10)
                {
                    //se descubre un caracter
                    if (pos < _partida.PosicionesADescubrir.Count)
                    {
                        this._palabraAMostrar = Util.obtenerPalabraFormateada(_palabraAMostrar, _partida.PalabraEnJuego, _partida.PosicionesADescubrir[pos]);
                        pos++;
                        NotifyPropertyChanged("PalabraAMostrar");
                    }
                }


                if (_timeMax <= 10)
                {
                    _timeMax--;
                    LblTemporizador = "0" + TimeMax.ToString();
                    NotifyPropertyChanged("LblTemporizador");
                }
                else
                {
                    _timeMax--;
                    LblTemporizador = _timeMax.ToString();
                    NotifyPropertyChanged("LblTemporizador");
                }
            }
            //else
            //{

            //    if (_timeMax == 0 || hanAcertadoTodos)
            //    {
            //        //TODO
            //        //El contador llega a 0


            //        //Bloquear el chat para todo el mundo en este tiempo
            //        //Ponemos el IsMiTurno a TRUE para que automáticamente se bloquee el input del chat
            //        //(porque esta bindeado con el converter de true to false
            //        visible = "Visible";
            //        NotifyPropertyChanged("Visible");
            //        this.IsMiTurno = true;
            //        NotifyPropertyChanged("IsMiTurno");
            //        //Con esto lo que pasa es que se va a habilitar el inktool bar para todos pero bueno no podrán chatear así que diwa

            //        //se reinicia esto
            //        pos = 0;

            //        //Se muestra la palabra
            //        this._palabraAMostrar = _partida.PalabraEnJuego;
            //        NotifyPropertyChanged("PalabraAMostrar");
            //        tiempoEspera--;
            //        NotifyPropertyChanged("tiempoEspera");

            //        if (tiempoEspera == 0)
            //        {
            //            this._dispatcherTimer.Stop();
            //            proxy.Invoke("miContadorHaLlegadoACero", _usuarioPropio.ConnectionID, _partida.NombreSala);
            //        }
            //    }
            //}
            if (_timeMax == 0 || hanAcertadoTodos)
            {
                //TODO
                //El contador llega a 0

                if (hanAcertadoTodos)
                {
                    this._timeMax   = 0;
                    LblTemporizador = _timeMax.ToString();
                    NotifyPropertyChanged("LblTemporizador");
                }


                //Bloquear el chat para todo el mundo en este tiempo
                //Ponemos el IsMiTurno a TRUE para que automáticamente se bloquee el input del chat
                //(porque esta bindeado con el converter de true to false
                visible = "Visible";
                NotifyPropertyChanged("Visible");
                this.IsMiTurno = true;
                NotifyPropertyChanged("IsMiTurno");
                //Con esto lo que pasa es que se va a habilitar el inktool bar para todos pero bueno no podrán chatear así que diwa

                //se reinicia esto
                pos = 0;

                //Se muestra la palabra
                this._palabraAMostrar = _partida.PalabraEnJuego;
                NotifyPropertyChanged("PalabraAMostrar");
                tiempoEspera--;
                NotifyPropertyChanged("tiempoEspera");

                if (tiempoEspera == 0)
                {
                    this._dispatcherTimer.Stop();
                    proxy.Invoke("miContadorHaLlegadoACero", _usuarioPropio.ConnectionID, _partida.NombreSala);
                }
            }
        }
예제 #41
0
            /// <summary>
            /// Constructor
            /// </summary>
            /// <param name="functionName">Function name</param>
            /// <param name="callback">Callback for data</param>
            /// <param name="delayMilliseconds">Delay after invoking each object[] in param, used if the server will disconnect you for too many invoke too fast</param>
            /// <param name="param">End point parameters, each array of strings is a separate call to the end point function. For no parameters, pass null.</param>
            /// <returns>Connection</returns>
            public async Task OpenAsync(string functionName, Func <string, Task> callback, int delayMilliseconds = 0, object[][] param = null)
            {
                callback.ThrowIfNull(nameof(callback), "Callback must not be null");

                SignalrManager _manager = this.manager;

                _manager.ThrowIfNull(nameof(manager), "Manager is null");

                Exception ex = null;

                param = (param ?? new object[][] { new object[0] });
                string functionFullName = _manager.GetFunctionFullName(functionName);

                this.functionFullName = functionFullName;

                while (true)
                {
                    await _manager.AddListener(functionName, callback, param);

                    try
                    {
                        // ask for proxy after adding the listener, as the listener will force a connection if needed
                        IHubProxy _proxy = _manager.hubProxy;
                        if (_proxy == null)
                        {
                            throw new ArgumentNullException("Hub proxy is null");
                        }

                        // all parameters must succeed or we will give up and try the loop all over again
                        for (int i = 0; i < param.Length; i++)
                        {
                            if (i != 0)
                            {
                                await Task.Delay(delayMilliseconds);
                            }
                            bool result = await _proxy.Invoke <bool>(functionFullName, param[i]).ConfigureAwait(false);

                            if (!result)
                            {
                                throw new APIException("Invoke returned success code of false");
                            }
                        }
                        break;
                    }
                    catch (Exception _ex)
                    {
                        // fail, remove listener
                        _manager.RemoveListener(functionName, callback);
                        ex = _ex;
                        Logger.Info("Error invoking hub proxy {0}: {1}", functionFullName, ex);
                        if (disposed || manager.disposed)
                        {
                            // give up, if we or the manager is disposed we are done
                            break;
                        }
                        else
                        {
                            // try again in a bit...
                            await Task.Delay(500);
                        }
                    }
                }

                if (ex == null)
                {
                    this.callback = callback;
                    lock (_manager.sockets)
                    {
                        _manager.sockets.Add(this);
                    }
                    return;
                }
            }
예제 #42
0
        public async Task <ActionResult> GenerateAnswer(ChatViewModel model)
        {
            // Iteracción entre el usuario y s@mi Bot

            // Variables tipo texto
            string textUser = model.Message, queryLuis = "", respuestaFinal = "", intencion = "", respuestaSami = "", entidad = "", casoJson = "", respuestaLuis = ""
            , puntajeLuis = "", puntajeQnA = "", respuesta = "";

            // Variables tipo texto array
            string[] returnLuisFormat = null;

            // Variables tipo enteros
            int operacionMatematica = 0;

            // Instancia con las APIS
            var bot = new ConnectToBot();

            var           uri          = new Uri(Request.Url.AbsoluteUri);
            List <string> exchangeRate = new List <string>();

            //Generate a URL from the URI
            var url = $"{uri.Scheme}://{uri.Host}:{uri.Port}";
            //Generate a hub client to specified url
            var hub = new HubConnection(url);

            //Generate a hub proxy to specified hub
            IHubProxy proxy = hub.CreateHubProxy("SamiChatHub");

            var datosSamiApi = (from samiapi in _db.ApiConversacions select samiapi).First();

            var resultadosApi = await bot.GetAnswersAsync(datosSamiApi.SamiApiKey
                                                          , datosSamiApi.SamiApiLink
                                                          , textUser
                                                          , model.CompanyId
                                                          , model.IdUserAspNetUser
                                                          , model.OS
                                                          , model.Name);

            model.RepliedByBot = false;

            casoJson      = resultadosApi.TipoCaso;
            respuesta     = resultadosApi.Respuesta;
            respuestaLuis = resultadosApi.FormatoLuis;
            intencion     = resultadosApi.Intencion;
            entidad       = resultadosApi.Entidades;
            puntajeLuis   = resultadosApi.PuntajeLuis;
            puntajeQnA    = resultadosApi.PuntajeQnA;

            /*
             * Aquí pasa la función para guardar a la tabla de reporte.
             */

            if (casoJson != "2" && casoJson != "5")
            {
                string[] convertido = respuestaSami.Split(new[] { "<script>" }, StringSplitOptions.None);

                var chatReportSami = SaveReportChatSami(model.IdSesionSaved, model.Name, model.IdUserAspNetUser, textUser, respuesta, respuestaLuis, model.OS, intencion, entidad, puntajeLuis, puntajeQnA, "Web");
            }


            switch (casoJson)
            {
            case "1":
                // Escenario sin paso de QnA: ¿Que necesitas de....?, ¿Qué necesitas ...?
                respuestaFinal = queryLuis + "<script>nextQuery();</script>";
                rating         = null;

                break;

            case "2":
                // Escenario respuesta del caso consultado.
                respuestaFinal = "Tengo resultado de tu ticket, estos son los datos: <br/></script><script>nextQuery();</script>";
                // Convertimos el archivo xml en texto
                XElement caResult = XElement.Parse(queryLuis);
                // Se toma solo las etiquetas <AttrValue></AttrValue>
                var att = caResult.Descendants("AttrValue").ToList();
                // Se crea un array de cadena de texto.
                string[] lista = { "<br/>Estado: ", "<br/>Caso Asignado a: ", "<br/>Descripción: " };
                // Se combina el resultado de CA con la cadena de Array
                var answerCA = att.Zip(lista, (n, w) => new { Number = n, Word = w });
                foreach (var nw in answerCA)
                {
                    // Se imprime los resultados junto con la cadena de array, aquí se elimina el <AttrValue></AttrValue>
                    respuestaFinal += String.Join(" ", nw.Word.ToString() + nw.Number.Value);
                }
                // Se desactiva panel de calificación.
                rating = null;

                break;

            case "3":

                //Escenario respuesta de QnA sin FeedBack

                respuestaFinal = respuesta + "<script>nextQuery();</script>";

                // Se desactiva el panel de calificación.
                rating = null;

                break;

            case "4":

                //Escenario de QnA con FeedBack

                respuestaFinal = respuesta;
                // Activa el panel de calificación
                rating = ReturnView();

                break;

            case "5":
                // Escenario pasa al agente automático.
                respuestaFinal = "No tengo una respuesta a tu pregunta en este momento.<script>AutoQueueForAgentChat();</script>";
                rating         = null;

                break;

            case "6":
                // Escenario pasa al agente automático.
                respuestaFinal = respuesta + "<script>AutoQueueForAgentChat();</script>";
                rating         = null;

                break;
            }
            //Start hub connection
            await hub.Start();

            //Set chat model values
            model.Name    = "Pólux";
            model.Message = respuestaFinal + $"<br/><small><b>LUIS: {respuestaLuis} <br/> PUNTAJE LUIS: {puntajeLuis} <br/> PUNTAJE QNA: {puntajeQnA}</b></small>";
            model.ProfilePictureLocation = "bot-avatar.png";
            //Send answer message
            await proxy.Invoke <ChatViewModel>("sendChatMessage2", model);

            //Send acceptable answer or switch to agent prompt
            if (rating != null)
            {
                // Tiempo de espera por longitud.
                operacionMatematica = respuestaFinal.Length * 50;
                Thread.Sleep(operacionMatematica);
                model.Message = rating;
                await proxy.Invoke <ChatViewModel>("sendChatMessage2", model);
            }
            //Stop hub connection
            hub.Stop();

            return(View(model));
        }
        /// <summary>
        /// Main method to fire up the SignalR client and initiate a connection to the ISAP hub.
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="locationIdentifier"></param>
        /// <param name="locationName"></param>
        /// <param name="applicationInstanceId"></param>
        /// <param name="application"></param>
        /// <param name="applicationVersion"></param>
        /// <param name="isLocalTestMode"></param>
        /// <returns></returns>
        public async Task <Exception> StartupClient(string username, string password, string locationIdentifier, string locationName, string applicationInstanceId, ProschlafUtils.GlobalEnums.ProschlafApplications application, string applicationVersion, bool isLocalTestMode = false)
        {
            if (hubConnection != null && hubConnection.State != ConnectionState.Disconnected)
            {
                return(new Exception("Client is already initialized and either connecting or already connected."));
            }

            string endpoint = (isLocalTestMode ? BASE_URL_LOCAL : BASE_URL_LIVE) + "signalr/";

            hubConnection = new HubConnection(endpoint);
            hubConnection.Headers.Add("username", username); //set mandatory auth header fields
            hubConnection.Headers.Add("password", password);
            hubConnection.Closed += HubConnection_Closed;
            myHub = hubConnection.CreateHubProxy("ApplicationHub"); //name of the specific hub on the server

            #region Register and implement methods defined by the server

            //register the "ReportStatus" method which can be called by the hub

            myHub.On(nameof(IApplicationClient.RequestStatusReport), () =>
            {
                ((IApplicationClient)this).RequestStatusReport();
                OnHubMessageReceived?.Invoke(this, new Tuple <string, string>(nameof(IApplicationClient.RequestStatusReport), null));
            });

            myHub.On(nameof(IApplicationClient.RequestTeamViewerStartup), () =>
            {
                ((IApplicationClient)this).RequestTeamViewerStartup();
                OnHubMessageReceived?.Invoke(this, new Tuple <string, string>(nameof(IApplicationClient.RequestTeamViewerStartup), null));
            });

            myHub.On(nameof(IApplicationClient.RequestSystemReboot), () =>
            {
                ((IApplicationClient)this).RequestSystemReboot();
                OnHubMessageReceived?.Invoke(this, new Tuple <string, string>(nameof(IApplicationClient.RequestSystemReboot), null));
            });

            /*
             * myHub.On<string>(nameof(IApplicationClient.ReportStatus), param =>
             * {
             *  OnHubMessageReceived?.Invoke(this, nameof(IApplicationClient.ReportStatus));
             * });
             */
            #endregion

            //start the connection to the hub
            Exception ex = await hubConnection.Start().ContinueWith(task =>
            {
                if (task.IsFaulted)
                {
                    return(new Exception("Exception while starting connection to: " + endpoint, task.Exception));
                }
                else
                {
                    return(null);
                }
            });

            if (ex != null)
            {
                return(ex);
            }

            if (hubConnection.State == ConnectionState.Disconnected)
            {
                return(new Exception("Connection was disconnected while starting connection to: " + endpoint, null));
            }

            //authenticate and register this client at the hub
            ex = await myHub.Invoke(nameof(IApplicationHub.AuthenticateAndRegisterClient), locationIdentifier, locationName, applicationInstanceId, application, applicationVersion).ContinueWith(task =>
            {
                if (task.IsFaulted)
                {
                    return(new Exception($"There was an error calling '{nameof(IApplicationHub.AuthenticateAndRegisterClient)}'", task.Exception));
                }
                else
                {
                    return(null);
                }
            });

            return(ex);
        }
 /// <summary>
 /// Posts a command result message to the hub (usually done after a function was called by the hub).
 /// </summary>
 /// <param name="result"></param>
 /// <returns></returns>
 public Task <Exception> PostCommandResult(SignalRCommandResult result)
 {
     myHub.Invoke(nameof(IApplicationHub.PostCommandResult), result);
     OnResultToHubSent?.Invoke(this, new Tuple <string, SignalRCommandResult>(nameof(IApplicationHub.PostCommandResult), result));
     return(null);
 }
예제 #45
0
 private async void Button_Click_1(object sender, RoutedEventArgs e)
 {
     await proxy.Invoke("Send", Input.Text);
 }
 public void NotifyGraphUpdate(List <NodeViewModel> nodes, List <RelationViewModel> relations)
 {
     Console.WriteLine($"Sending graph update to Graph Hub");
     _proxy.Invoke <string>("NotifyGraphUpdate", nodes, relations).Wait();
 }
예제 #47
0
        private void ProsesTimeAlertNotif()
        {
            ContextModel dbcontext     = new ContextModel();
            string       baseUrl       = System.Configuration.ConfigurationManager.AppSettings["baseUrl"];
            var          hubConnection = new HubConnection(baseUrl + "signalr", useDefaultUrl: false);
            IHubProxy    alphaProxy    = hubConnection.CreateHubProxy("NotificationHub");

            hubConnection.Start().Wait();

            var dataNotif = dbcontext.ListNotif.Where(d => !d.IsSend).ToList();

            foreach (var item in dataNotif)
            {
                List <TimeAlert> dataAlert = dbcontext.TimeAlert.Where(d => d.idProses == item.Type && d.status).ToList();
                foreach (var itemAlert in dataAlert)
                {
                    DateTime currDateNotif = DateTime.Now;
                    if (itemAlert.overSatuan == "Menit")
                    {
                        currDateNotif = item.CreateDate.AddMinutes(itemAlert.over);
                    }
                    else if (itemAlert.overSatuan == "Jam")
                    {
                        currDateNotif = item.CreateDate.AddHours(itemAlert.over);
                    }
                    else if (itemAlert.overSatuan == "Hari")
                    {
                        currDateNotif = item.CreateDate.AddDays(itemAlert.over);
                    }

                    if (currDateNotif <= DateTime.Now)
                    {
                        foreach (var user in itemAlert.idUserAlert.Split(','))
                        {
                            if (itemAlert.AlertPopup)
                            {
                                alphaProxy.Invoke("SendNotifications", item.PopupMsg, user);
                            }
                            if (itemAlert.AlertEmail)
                            {
                                int idUser = int.Parse(user);
                                var users  = dbcontext.User.Find(idUser);
                                if (users.Email != null && users.Email != "")
                                {
                                    alphaProxy.Invoke("SendNotificationEmail", users.Email, "Alert TMS MKA", item.EmailMsg);
                                }
                            }
                            if (itemAlert.AlertSound)
                            {
                                alphaProxy.Invoke("SendNotificationSound", user);
                            }
                        }

                        item.IsSend = true;
                        dbcontext.ListNotif.Attach(item);
                        var entry = dbcontext.Entry(item);
                        entry.State = EntityState.Modified;
                        dbcontext.SaveChanges();
                    }
                }
            }
            dbcontext.Dispose();
        }
예제 #48
0
 /// <summary>
 /// Invokes the specified hub method without expecting a return value.
 /// </summary>
 /// <param name="methodName">Name of the method.</param>
 /// <param name="args">The arguments.</param>
 /// <returns></returns>
 public Task InvokeAsync(string methodName, params object[] args)
 {
     return(_proxy?.Invoke(methodName, args));
 }
예제 #49
0
 private void EditProfitLimit()
 {
     _hub.Invoke("EditProfitLimit", SelectedUser.Login, SelectedUser.ProfitLimit);
 }
예제 #50
0
        public async void SendMessage(string message)
        {
            await _hubConnection.Start();

            await _chatHubProxy.Invoke("Send", message);
        }
예제 #51
0
        private async void ConnectToServer(string userLog, string passwordLog)
        {
            nameText.Text = "Username: "******"signalr", "&name=" + userLog + "&password="******"MyHub");
            chatHubProxy.On <string, string, string>("addMessage", (user, message, msgTo) =>
            {
                Console.WriteLine(message + " at console");
                if (userLog.Equals(user))
                {
                    chatHandler(msgTo, "You", message, msgTo);
                    chatText.Append("You to " + msgTo + ": " + message + "\n");
                }
                else
                {
                    if (userLog.Equals(msgTo))
                    {
                        chatHandler(user, user, message, msgTo);
                    }
                    else
                    {
                        chatHandler(msgTo, user, message, msgTo);
                    }
                    if (who.Equals(msgTo) || who.Equals(user))
                    {
                        chatText.Append(user + " to " + msgTo + ": " + message + "\n");
                    }
                    else
                    {
                        chatText.Append("New message from " + user + " to " + msgTo + "\n");
                    }
                }
            });

            await 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);
                }
            });

            allChats.Add("freeGroup", new StringBuilder(""));
            GetUserList();

            FindViewById <Button>(Resource.Id.buttonSend).Click += async(o, args) =>
            {
                try
                {
                    var messages = FindViewById <EditText>(Resource.Id.editTextMessage).Text;
                    await chatHubProxy.Invoke("SendChatMessage", new object[] { who, userLog, messages });

                    if (!who.Equals("freeGroup"))
                    {
                        chatText.Append("You to " + who + ": " + messages + "\n");
                        chatHandler(who, "You", messages, who);
                    }
                } catch (Exception ex)
                {
                    Console.WriteLine("Server unreachable");
                    chatText.Append("Server unreachable\n");
                }
            };
        }
예제 #52
0
 public void SignIn(string currentUser, string targetUser)
 {
     chatHubProxy.Invoke("SignIn", currentUser, targetUser);
 }
예제 #53
0
 public Task SendExecutionRequest(ReportExecutionResultSet executeRequest)
 {
     return(hubProxy.Invoke("BeginRequestExecution", executeRequest));
 }
예제 #54
0
 /// <summary>
 /// Get auth context
 /// </summary>
 /// <param name="apiKey">API key</param>
 /// <returns>String</returns>
 public async Task <string> GetAuthContext(string apiKey) => await hubProxy.Invoke <string>("GetAuthContext", apiKey);
예제 #55
0
 /// <summary>
 /// recycles the chat message without recycling the message prompt.
 /// this was needed because the message prompt was causing the background worker
 /// to wait indefinitely.
 /// </summary>
 /// <param name="message"></param>
 /// <param name="excludeSelf"></param>
 private static void SendChatMessage(string message, bool excludeSelf)
 {
     _chatHub.Invoke("SendChatMessage", message, excludeSelf, true);
 }
예제 #56
0
        private async void OnEnviar()
        {
            await _hub.Invoke("Send", usuario.Nome, Mensagem);

            Mensagem = string.Empty;
        }
예제 #57
0
        public MainWindowViewModel(IDialogCoordinator dialog, IHubProxy hub, HubConnection connection, Window window)
        {
            Connection               = connection;
            Connection.Reconnected  += ConnectionOnReconnected;
            Connection.StateChanged += ConnectionOnStateChanged;
            Hub                    = hub;
            Dialog                 = dialog;
            AdminViewModel         = new AdminViewModel(Hub, DialogCoordinator.Instance);
            _flashWindowHelper     = new FlashWindowHelper(Application.Current);
            _thisWindow            = window;
            MenuItemConnectCommand = new Command(arg => Show_LoginForm());
            SecurityChooseCommand  = new Command(SecurityChoose);
            SecuritiesCommand      = new Command(arg => GetSecurities());
            OpenWindowCommand      = new Command(OpenWindow);
            ChangePassCommand      = new Command(arg => ChangePass());
            SleepCommand           = new Command(arg => SelfSleep());
            SaveWorkspaceCommand   = new Command(arg => SaveWorkspace());
            LoadWorkspaceCommand   = new Command(arg => LoadWorkspace());
            Status                 = "Status: Disconnected";
            //get watchlists collection and initialize watcher to monitor changes in the watchlists' folder
            GetWatchlists();
            InitializeWatcher();
            SecVm.WatchListsCollection = WatchListsCollection;
            //Subscribing to events
            TXmlConnector.SendNewFormData += XmlConnector_OnSendNewFormData; //general data
            /*TXmlConnector.SendNewStatus += XmlConnector_OnSendNewStatus;*/ //status
            TXmlConnector.SendStatus      += XmlConnector_OnSendNewStatus;
            TXmlConnector.SendNewSecurity += XmlConnector_OnSendNewSecurity; //securities
            TXmlConnector.ConnectorSetCallback();
            TXmlConnector.FormReady = true;

            //Initializing the connector dll
            var path = (Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\Inside MMA\\logs\\" + ClientInfo.InsideLogin).Replace("\\", "//");

            Directory.CreateDirectory(path);
            foreach (var file in new DirectoryInfo(path).GetFiles())
            {
                file.Delete();
            }
            //loading settings
            WindowDataHandler.GetWindowData();
            Settings.Default.Reload();
            Level2Settings.Default.Reload();
            //path = path.Substring(0, path.LastIndexOf('\\') + 1) + "\0";
            if (TXmlConnector.ConnectorInitialize(path, (short)Settings.Default.LogLevel))
            {
                TXmlConnector.StatusDisconnected.Set();
            }

            //setting the number decimal separator to a point
            var customCulture = (CultureInfo)Thread.CurrentThread.CurrentCulture.Clone();

            customCulture.NumberFormat.NumberDecimalSeparator = ".";
            CultureInfo.DefaultThreadCurrentCulture           = customCulture;
            Thread.CurrentThread.CurrentCulture = customCulture;

            //subbing for singlar events
            Hub?.On("Sleep", Sleep);
            Hub?.On("Unsleep", Unsleep);
            Hub?.On("SelectWindows", WindowAvailabilityManager.SelectWindows);
            Hub?.On("Disconnect", DisconnectByServer);
            Hub?.On("DisplayMessage", DisplayMessage);
            Hub?.On("CancelOrders", ClientOrdersViewModel.CancelAllOrdersMethod);
            Hub?.On("CancelStoporders", ClientOrdersViewModel.CancelAllStopordersMethod);
            Hub?.On("CloseBalance", ClientsViewModel.CloseBalanceMethod);
            //requesting license exp date
            Hub?.On("License", GetLicense);
            Hub?.Invoke("GetLicense");
            //setting the stoporder manager
            new OrderManager(ClientOrdersViewModel.ClientStoporders, ClientOrdersViewModel.ClientOrders);
            //setting the report manager
            ReportManager.Set();
            ShowPatchnotes();
        }
예제 #58
0
 public async Task <List <User> > LoginAsync(string name, byte[] photo)
 {
     return(await hubProxy.Invoke <List <User> >("Login", new object[] { name, photo }));
 }
예제 #59
0
        /// <summary>
        /// Start the hub connection - populate FunctionNamesToFullNames first
        /// </summary>
        /// <returns></returns>
        public async Task StartAsync()
        {
            // stop any previous hub connection
            hubConnection?.Stop();
            hubConnection?.Dispose();

            // make a new hub connection
            hubConnection         = new HubConnection(ConnectionUrl, false);
            hubConnection.Closed += SocketClosed;

#if DEBUG
            //hubConnection.TraceLevel = TraceLevels.All;
            //hubConnection.TraceWriter = Console.Out;
#endif

            hubProxy = hubConnection.CreateHubProxy(HubName);
            if (hubProxy == null)
            {
                throw new APIException("CreateHubProxy - proxy is null, this should never happen");
            }

            // assign callbacks for events
            foreach (string key in FunctionNamesToFullNames.Keys)
            {
                hubProxy.On(key, async(string data) => await HandleResponse(key, data));
            }

            // create a custom transport, the default transport is really buggy
            DefaultHttpClient client = new DefaultHttpClient();
            customTransport = new WebsocketCustomTransport(client, ConnectInterval, KeepAlive);
            var autoTransport = new AutoTransport(client, new IClientTransport[] { customTransport });
            hubConnection.TransportConnectTimeout = hubConnection.DeadlockErrorTimeout = TimeSpan.FromSeconds(10.0);

            // setup connect event
            customTransport.WebSocket.Connected += async(ws) =>
            {
                SignalrSocketConnection[] socketsCopy;
                lock (sockets)
                {
                    socketsCopy = sockets.ToArray();
                }
                foreach (SignalrSocketConnection socket in socketsCopy)
                {
                    await socket.InvokeConnected();
                }
            };

            // setup disconnect event
            customTransport.WebSocket.Disconnected += async(ws) =>
            {
                try
                {
                    SignalrSocketConnection[] socketsCopy;
                    lock (sockets)
                    {
                        socketsCopy = sockets.ToArray();
                    }
                    foreach (SignalrSocketConnection socket in socketsCopy)
                    {
                        await socket.InvokeDisconnected();
                    }
                }
                catch (Exception ex)
                {
                    Logger.Info(ex.ToString());
                }
                // start a task to tear down the hub connection
                await Task.Run(() =>
                {
                    try
                    {
                        // tear down the hub connection, we must re-create it whenever a web socket disconnects
                        hubConnection?.Dispose();
                    }
                    catch (Exception ex)
                    {
                        Logger.Info(ex.ToString());
                    }
                });
            };
            await hubConnection.Start(autoTransport);

            // get list of listeners quickly to limit lock
            HubListener[] listeners;
            lock (this.listeners)
            {
                listeners = this.listeners.Values.ToArray();
            }

            // re-call the end point to enable messages
            foreach (var listener in listeners)
            {
                foreach (object[] p in listener.Param)
                {
                    await hubProxy.Invoke <bool>(listener.FunctionFullName, p);
                }
            }
        }
예제 #60
0
 public void SendCreatedAirplane(Airplane airplane)
 {
     proxy.Invoke("SendPlane", airplane);
 }