/// <summary> /// Adds a metric observer to a resource. /// </summary> /// <param name="resourceUriString">Unique URI that identifies the resource.</param> /// <param name="lifetime">The lifetime of the lease.</param> /// <param name="observer">Metric observer to receive events.</param> /// <returns>A unique string for the lease key, which is used to refresh the lease for the observer.</returns> public async Task <string> AddResourceObserverAsync(string resourceUriString, TimeSpan lifetime, MetricObserver observer) { IMetricObserver objRef = await client.CreateObjectReference <IMetricObserver>(observer); IPiSystem resource = GetPiSystem(resourceUriString); return(await resource.AddObserverAsync(lifetime, objRef)); }
public async Task <string> Get(int id) { // HACK: testing code below var test = new TestListener(); var testWrap = await ClusterClient.CreateObjectReference <IRegistryListener <Guid, AgentInfo> >(test); var x = ClusterClient.GetGrain <IRegistry <Guid, AgentInfo> >(0); await x.Subscribe((k, v) => k == Guid.Empty, testWrap, "test"); return("value"); }
public async Task RunAsync() { ShowHelp(true); while (true) { var command = System.Console.ReadLine(); if (command == null) { continue; } if (command == "/help") { ShowHelp(); } else if (command == "/quit") { await _host.StopAsync(); } else if (command.StartsWith("/login")) { var match = Regex.Match(command, @"/login (?<userId>\w{1,100})"); if (match.Success) { _userId = match.Groups["userId"].Value; _userGrain = _client.GetGrain <IUserGrain>(_userId); if (_viewer == null) { _viewer = await _client.CreateObjectReference <IMessageViewer>(new MessageConsoleViewer()); } await _userGrain.LoginAsync(_viewer); System.Console.WriteLine($"The current user is now [{_userId}]"); var offlineMessages = await _userGrain.GetOfflineMessages(); System.Console.WriteLine($"Receive offline messages: {offlineMessages.Count}"); foreach (var message in offlineMessages) { System.Console.WriteLine($"Receive {message.TargetId}: {message.Content}"); } } } else if (command.StartsWith("/send")) { var match = Regex.Match(command, @"/send (?<userId>\w{1,100}) (?<message>.+)"); if (match.Success) { var targetUserId = match.Groups["userId"].Value; var message = match.Groups["message"].Value; await _userGrain.SendMessageAsync(new TextMessage(_userId, targetUserId, message)); System.Console.WriteLine($"Send {targetUserId} the new message!"); } else { System.Console.WriteLine("Invalid send. Try again or type /help for a list of commands."); } } } }
public ClientSession(ISocketTask socket, Guid sessionID, IClusterClient clusterClient) { m_Socket = socket; SessionID = sessionID; socket.MessageEncoder = new MessageEncoder(); socket.MessageDecoder = new MessageDecoder(); m_Socket.OnDisconnect += OnDisconnect; m_Socket.OnMessage += OnMessage; try { m_ClientSessionGrain = clusterClient.GetGrain <IPlayerGrain>(sessionID); var obj = clusterClient.CreateObjectReference <IGatewayGrainObserver>(this).GetAwaiter().GetResult(); m_ClientSessionGrain.Subscribe(obj).Wait(); } catch (Exception e) { Logger.Warn(e); } socket.Startup(); }
private static async Task DoClientSpyWork(IClusterClient client, JObject Message) { var deviceSerialNumber = Message.GetValue("src").ToString(); var friend = client.GetGrain <IDevice>(deviceSerialNumber); int x = await friend.GetPendingOperationsCount(); Console.WriteLine("friend.GetPrimaryKeyString: " + friend.GetPrimaryKeyString()); Console.WriteLine("Count: " + x); Console.WriteLine("ALARM TRACER - Evaluate ALARM and increment PendingOperations"); var response = await friend.Evaluate(Message.ToString()); Forwarder f = new Forwarder(); //Create a reference for chat usable for subscribing to the observable grain. var obj = await client.CreateObjectReference <IDeviceObserver>(f); //Subscribe the instance to receive messages. await friend.Subscribe(obj); Console.ReadLine(); }
private static void SubscribeToMessageNotifications(IClusterClient client, ChatRoom chatRoom, IChatRoomGrain chatRoomGrain) { var msgHub = new MessageHub(chatRoom); var msgHubObj = client.CreateObjectReference <IMessageHub>(msgHub).Result; chatRoomGrain.Subscribe(msgHubObj); }
public async Task StartAsync(CancellationToken cancellationToken) { // the load generator will update player ids within a range that includes this player var playerId = new Guid("{2349992C-860A-4EDA-9590-000000000006}"); var player = _client.GetGrain <IPlayerGrain>(playerId); // poll for this player to join a game while (_game == null) { _logger.LogInformation("Getting current game for player {@PlayerId}...", playerId); try { _game = await player.GetCurrentGameAsync(); } catch (Exception error) { _logger.LogError(error, "Error while requesting current game for player {@PlayerId}", playerId); } if (_game == null) { try { await Task.Delay(1000, cancellationToken); } catch (OperationCanceledException) { return; } } } _logger.LogInformation("Observing updates for game {@GameKey}", _game.GetPrimaryKey()); // subscribe for updates var reference = await _client.CreateObjectReference <IGameObserver>(_observer); await _game.ObserveGameUpdatesAsync(reference); _logger.LogInformation("Subscribed successfully to game {@GameKey}", _game.GetPrimaryKey()); }
/// <summary> /// 发送 /// </summary> /// <param name="client"></param> /// <returns></returns> private static async Task DoClientWork(IClusterClient client) { var friend = client.GetGrain <IHello>(new Guid()); var chat = new Chat(); var obj = await client.CreateObjectReference <IChat>(chat); await friend.Subscribe(obj); await friend.SendUpdateMessage($"你好!{DateTime.Now}"); }
private async Task StartWatcherAsync() { // observing a hardcoded player id for sample purposes // the load generator will update player ids within a range that includes this player var playerId = new Guid("{2349992C-860A-4EDA-9590-000000000006}"); var player = client.GetGrain <IPlayerGrain>(playerId); IGameGrain game = null; // poll for this player to join a game while (game == null) { logger.LogInformation("Getting current game for player {@PlayerId}...", playerId); try { game = await player.GetCurrentGameAsync(); } catch (Exception error) { logger.LogError(error, "Error while requesting current game for player {@PlayerId}", playerId); } if (game == null) { try { await Task.Delay(1000, startCancellation.Token); } catch (OperationCanceledException) { return; } } } logger.LogInformation("Observing updates for game {@GameKey}", game.GetPrimaryKey()); // subscribe for updates var watcher = client.ServiceProvider.GetService <IGameObserver>(); await game.ObserveGameUpdatesAsync( await client.CreateObjectReference <IGameObserver>(watcher)); logger.LogInformation("Subscribed successfully to game {@GameKey}", game.GetPrimaryKey()); }
private static async Task DoClientWork(IClusterClient client) { //var restclient = new RestClient("https://prod-34.westeurope.logic.azure.com:443/"); //var request = new RestRequest("workflows/ae8551b470da49078596ab10638bfe58/triggers/manual/paths/invoke?api-version=2016-10-01&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=weyC2_LkTjaX81VmnRzimnsyuYj1F3MUp3hDuQsiLrQ", Method.POST); //request.AddParameter("application/json", new JObject() , ParameterType.RequestBody); //request.RequestFormat = DataFormat.Json; //var res = restclient.Execute(request, Method.POST); //Console.WriteLine("response.StatusCode : " + res.StatusCode); // example of calling grains from the initialized client var friend = client.GetGrain <IDevice>("SN00001"); int x = await friend.GetPendingOperationsCount(); Console.WriteLine("friend.GetPrimaryKeyString: " + friend.GetPrimaryKeyString()); Console.WriteLine("Count: " + x); Forwarder f = new Forwarder(); //Create a reference for chat usable for subscribing to the observable grain. var obj = await client.CreateObjectReference <IDeviceObserver>(f); //Subscribe the instance to receive messages. //string response = await friend.Evaluate("{'pippo':'pluto'}"); await friend.Subscribe(obj); //while (true) { // await friend.Subscribe(obj); // // send a publish // await friend.Publish("aiuto!!!! Spegni la macchina, chiama il prete!", "HW001"); // Thread.Sleep(5000); //} //Console.WriteLine(response); Console.ReadLine(); }
public override bool Init() { m_ClusterClient = InitialiseClient(); m_MainEntry = m_ClusterClient.GetGrain <IMainEntry>(0); m_SiloGateWay_Obs = new SiloGateWay_Obs(); m_IGateWay_Obs = m_ClusterClient.CreateObjectReference <IGateWay_Obs>(m_SiloGateWay_Obs).Result; m_IGateWay = m_MainEntry.GetIGateWay().Result; m_IGateWay.SubscribeAsync(m_IGateWay_Obs).Wait(); m_ChatRoom = m_MainEntry.GetIChatRoom().Result; return(base.Init()); }
private async Task<ObserverInfo> GetOrAdd<TObserver, IObserver>(string key) where TObserver : class, IObserver, new() where IObserver : IGrainObserver { ObserverInfo info; if (this.observers.ContainsKey(key)) { info = this.observers[key]; } else { TObserver obsvr = (TObserver)Activator.CreateInstance(typeof(TObserver)); IObserver refer = await cluster.CreateObjectReference<IObserver>(obsvr); info = new ObserverInfo() { value = obsvr, reference = refer, cc = 0 }; this.observers.Add(key, info); } return info; }
public async Task PerformFunction(IClusterClient clusterClient) { Console.WriteLine("Observing for behavior, stops once behavior observed."); var observerManager = clusterClient.GetGrain <IObservableManager>(0); var observerRef = await clusterClient .CreateObjectReference <IObserverSample>(this); while (!_shouldBreakLoop) { await observerManager.Subscribe(observerRef); await Task.Delay(5000); } await observerManager.Unsubscribe(observerRef); ConsoleHelpers.ReturnToMenu(); }
public async Task RunAsync() { ShowHelp(true); while (true) { var command = System.Console.ReadLine(); if (command == null) { continue; } if (command == "/help") { ShowHelp(); } else if (command == "/quit") { await _host.StopAsync(); } else if (command == "/exit") { System.Console.WriteLine($"Exit chat with {_targetUserId} ====================================================="); _targetUserId = string.Empty; System.Console.ForegroundColor = ConsoleColor.White; } else if (command.StartsWith("/chat")) { if (!IsLogin()) { System.Console.ForegroundColor = ConsoleColor.Red; System.Console.WriteLine("You need to login first"); System.Console.ForegroundColor = ConsoleColor.White; } var match = Regex.Match(command, @"/chat (?<userId>\w{1,100})"); if (match.Success) { _targetUserId = match.Groups["userId"].Value; System.Console.WriteLine($"Start chat with {_targetUserId} ====================================================="); } } else if (command.StartsWith("/login")) { if (IsLogin()) { System.Console.ForegroundColor = ConsoleColor.Red; System.Console.WriteLine("You have already login"); System.Console.ForegroundColor = ConsoleColor.White; continue; } var match = Regex.Match(command, @"/login (?<userId>\w{1,100})"); if (match.Success) { _userId = match.Groups["userId"].Value; _userGrain = _client.GetGrain <IUserGrain>(_userId); if (_viewer == null) { _viewer = await _client.CreateObjectReference <IMessageViewer>(new MessageConsoleViewer()); } await _userGrain.LoginAsync(_viewer); System.Console.Title = _userId; System.Console.WriteLine($"The current user is now [{_userId}]"); } } else { if (IsInChat()) { await _userGrain.SendMessageAsync(Message.CreateText(_userId, _targetUserId, command)); System.Console.ForegroundColor = ConsoleColor.Yellow; System.Console.WriteLine($"{_userId}: {command}"); System.Console.ForegroundColor = ConsoleColor.White; } } } }
public async Task RunAsync(IClusterClient client) { this.ShowHelp(true); while (true) { var command = Console.ReadLine(); if (command == "/help") { this.ShowHelp(); } else if (command == "/quit") { return; } else if (command.StartsWith("/user ")) { var match = Regex.Match(command, @"/user (?<username>\w{1,100})"); if (match.Success) { await this.Unobserve(); var username = match.Groups["username"].Value; this.account = client.GetGrain <IChirperAccount>(username); Console.WriteLine($"The current user is now [{username}]"); } else { Console.WriteLine("Invalid username. Try again or type /help for a list of commands."); } } else if (command.StartsWith("/follow ")) { if (this.EnsureActiveAccount()) { var match = Regex.Match(command, @"/follow (?<username>\w{1,100})"); if (match.Success) { var targetName = match.Groups["username"].Value; await this.account.FollowUserIdAsync(targetName); Console.WriteLine($"[{this.account.GetPrimaryKeyString()}] is now following [{targetName}]"); } else { Console.WriteLine("Invalid target username. Try again or type /help for a list of commands."); } } } else if (command == "/following") { if (this.EnsureActiveAccount()) { (await this.account.GetFollowingListAsync()) .ForEach(_ => Console.WriteLine(_)); } } else if (command == "/followers") { if (this.EnsureActiveAccount()) { (await this.account.GetFollowersListAsync()) .ForEach(_ => Console.WriteLine(_)); } } else if (command == "/observe") { if (this.EnsureActiveAccount()) { if (this.viewer == null) { this.viewer = await client.CreateObjectReference <IChirperViewer>(new ChirperConsoleViewer(this.account.GetPrimaryKeyString())); } await this.account.SubscribeAsync(this.viewer); Console.WriteLine($"Now observing [{this.account.GetPrimaryKeyString()}]"); } } else if (command == "/unobserve") { if (this.EnsureActiveAccount()) { await this.Unobserve(); } } else if (command.StartsWith("/unfollow ")) { if (this.EnsureActiveAccount()) { var match = Regex.Match(command, @"/unfollow (?<username>\w{1,100})"); if (match.Success) { var targetName = match.Groups["username"].Value; await this.account.UnfollowUserIdAsync(targetName); Console.WriteLine($"[{this.account.GetPrimaryKeyString()}] is no longer following [{targetName}]"); } else { Console.WriteLine("Invalid target username. Try again or type /help for a list of commands."); } } } else if (command.StartsWith("/chirp ")) { if (this.EnsureActiveAccount()) { var match = Regex.Match(command, @"/chirp (?<message>.+)"); if (match.Success) { var message = match.Groups["message"].Value; await this.account.PublishMessageAsync(message); Console.WriteLine("Published the new message!"); } else { Console.WriteLine("Invalid chirp. Try again or type /help for a list of commands."); } } } else { Console.WriteLine("Unknown command. Type /help for list of commands."); } } }