public static RecordItemResult genRecordItemResult(Guid recordKey, IUserGrain reporter, Random random) { var result = (random.Next(0, 3) == 0); // one third are positive var recordResult = new RecordItemResult(recordKey, reporter, SecurityLevel.Private, result); return(recordResult); }
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 RecordItemResult(Guid recordKey, IUserGrain reporter, SecurityLevel securityLabel, bool testResult) { RecordKey = recordKey; Reporter = reporter; SecurityLabel = securityLabel; Timestamp = DateTime.UtcNow; TestResult = testResult; }
public PlayerData(IUserGrain user) { User = user; _curBlood = MaxBlood; JumpTime = DateTime.MinValue; BigSkillTime = DateTime.MinValue; SkillCTime = DateTime.MinValue; SkillXTime = DateTime.MinValue; SkillZTime = DateTime.MinValue; }
protected RecordItem(Guid key, IPatientGrain patient, IUserGrain reporter, SecurityLevel securityLabel, string description, RecordType type, DateTime timestamp, RecordItemResult result) { Key = key; Patient = patient; Reporter = reporter; SecurityLabel = securityLabel; Description = description; Type = type; Timestamp = timestamp; Result = result; }
// 在这里添加 Actions public async Task <IActionResult> Index() { IUserGrain user = Startup.SlioClient.GetGrain <IUserGrain>(1); var items = await user.GetTodoItemsAsync(); var model = new TodoViewModel() { Items = items }; return(View(model)); }
public async Task GewinnVerteilung() { var aktionProUser = this._Abstimmung.State.AktionProUser; var aktionenDerUser = aktionProUser.Where(kv => !string.IsNullOrEmpty(kv.Value)).ToList(); var aktionen = AktionenModel.GetAktionen(); var count = aktionenDerUser.Count; if (count > 0) { var grpByAktion = aktionenDerUser.GroupBy(i => i.Value); var maxCount = grpByAktion.Max(grp => grp.Count()); var gewinnerAktionen = grpByAktion.Where(grp => (grp.Count() == maxCount)) .Select(grp => grp.Key) .ToDictionary(aktion => aktion, aktion => aktionen.FindAktion(aktion)); var verliehrerAktion = new AktionModel(string.Empty, 0, 0f, 0f, 0f, false); var nichtTeilnehmerAktion = new AktionModel(string.Empty, 0, 0f, 0f, 0f, false); var gewinnerAktion = new AktionModel(string.Empty, 0, 0f, 0f, 0f, false); var gesammtAktion = new AktionModel(string.Empty, 0, 0f, 0f, 0f, false); foreach (var aktuelleGewinnerAktion in gewinnerAktionen.Where(kv => (kv.Value is object) && (kv.Value.ForAll))) { nichtTeilnehmerAktion.AddGesammtTeilnehmer(aktuelleGewinnerAktion.Value !); verliehrerAktion.AddGesammtTeilnehmer(aktuelleGewinnerAktion.Value !); gewinnerAktion.AddGesammtTeilnehmer(aktuelleGewinnerAktion.Value !); } foreach (var aktuelleGewinnerAktion in gewinnerAktionen.Where(kv => (kv.Value is object) && (!kv.Value.ForAll))) { nichtTeilnehmerAktion.AddNichtTeilnehmer(aktuelleGewinnerAktion.Value !); verliehrerAktion.AddVerliehrer(aktuelleGewinnerAktion.Value !); gewinnerAktion.AddGewinner(aktuelleGewinnerAktion.Value !); } foreach (var kv in aktionProUser.ToList()) { var userId = kv.Key; IUserGrain userGrain = this.GrainFactory.GetGrain <IUserGrain>(userId); if (string.IsNullOrEmpty(kv.Value)) { await userGrain.GewinnVerteilung(nichtTeilnehmerAktion); } else if (gewinnerAktionen.TryGetValue(kv.Value, out var aktion)) { await userGrain.GewinnVerteilung(gewinnerAktion); } else { await userGrain.GewinnVerteilung(verliehrerAktion); } aktionProUser[userId] = string.Empty; } await this._Abstimmung.WriteStateAsync(); } }
public async Task PlayerSendMsg(IUserGrain user, string msg) { S2C100008 content = new S2C100008(); content.UserId = user.GetPrimaryKeyLong(); content.Content = msg; MOMsg notify = new MOMsg(); notify.ActionId = 100008; notify.Content = content.ToByteString(); await RoomNotify(notify); }
public async Task PlayerEnterRoom(IUserGrain user) { if (!_players.ContainsKey(user.GetPrimaryKeyLong())) { _players[user.GetPrimaryKeyLong()] = new PlayerData(user); } await user.SubscribeRoom(_stream.Guid); { S2C100001 content = new S2C100001(); content.RoomId = (int)this.GetPrimaryKeyLong(); foreach (var item in _players) { PlayerData player = null; if (_players.TryGetValue(item.Key, out player)) { var userPoint = new UserTransform(); userPoint.UserId = item.Key; userPoint.UserName = await player.User.GetNickName(); userPoint.Position = new MsgVector3(); userPoint.Position.X = player.Position.X; userPoint.Position.Y = player.Position.Y; userPoint.Position.Z = player.Position.Z; userPoint.Rotation = new MsgVector3(); userPoint.Rotation.X = player.Rotate.X; userPoint.Rotation.Y = player.Rotate.Y; userPoint.Rotation.Z = player.Rotate.Z; content.UserTransforms.Add(userPoint); } } MOMsg msg = new MOMsg(); msg.ActionId = 100001; msg.Content = content.ToByteString(); await user.Notify(msg); } { S2C100002 content = new S2C100002(); content.UserId = user.GetPrimaryKeyLong(); content.RoomId = (int)this.GetPrimaryKeyLong(); content.UserName = await user.GetNickName(); MOMsg msg = new MOMsg(); msg.ActionId = 100002; msg.Content = content.ToByteString(); await RoomNotify(msg); } }
public async Task PlayerLeaveRoom(IUserGrain user) { S2C100006 content = new S2C100006(); content.UserId = user.GetPrimaryKeyLong(); content.RoomId = (int)this.GetPrimaryKeyLong(); MOMsg msg = new MOMsg(); msg.ActionId = 100006; msg.Content = content.ToByteString(); await RoomNotify(msg); _players.Remove(user.GetPrimaryKeyLong()); await user.UnsubscribeRoom(); }
public static RecordItem genRecordItem(Guid guid, IPatientGrain patient, IUserGrain reporter, Random random) { var type = (RecordType)random.Next(0, 2); var record = new RecordItem(guid, patient, reporter, SecurityLevel.Private, "Random description", type); // half of the records have results with them if (random.Next(0, 2) == 0) { var RecordItemResult = genRecordItemResult(guid, reporter, random); return(record.WithResult(RecordItemResult)); } return(record); }
/// <summary> /// Get messages from all the user its subscriptions, /// combine them with its own messages, /// sort by timestamp and return the first limit number. /// </summary> public async Task <Timeline> GetTimeline(int limit) { // i) request a number of messages from each subscription var Tasks = State.Subscriptions.Select(UserName => { IUserGrain user = GrainFactory.GetGrain <IUserGrain>(UserName); return(user.GetMessages(limit)); }).ToList(); // ii) request your own messages Tasks.Add(GetMessages(limit)); // iii) await for all the messages and flatten them List <Message> Msgs = (await Task.WhenAll(Tasks)).SelectMany((x) => x).ToList(); // iv) order by Timestamp and take the first <limit> messages return(new Timeline(Name, Msgs.OrderBy((m) => m.Timestamp).Take(limit).ToList())); }
public Task PlayerCommand(IUserGrain user, List <CommandInfo> commands) { PlayerData commandPlayer; if (!_players.TryGetValue(user.GetPrimaryKeyLong(), out commandPlayer)) { return(Task.CompletedTask); } if (IsJumping(commandPlayer)) { return(Task.CompletedTask); } commands.ForEach(m => { m.UserId = user.GetPrimaryKeyLong(); _commands.Enqueue(m); }); return(Task.CompletedTask); }
public Task <Guid> JoinHall(IUserGrain user) { _userDict[user.GetPrimaryKeyLong()] = user; return(Task.FromResult(_stream.Guid)); }
public RecordItem(Guid key, IPatientGrain patient, IUserGrain reporter, SecurityLevel securityLabel, string description, RecordType type) : this(key, patient, reporter, securityLabel, description, type, DateTime.UtcNow, null) { }
public Task <Guid> LeaveHall(IUserGrain user) { _userDict.Remove(user.GetPrimaryKeyLong()); return(Task.FromResult(_stream.Guid)); }
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 Reconnect(IUserGrain user) { await user.SubscribeRoom(_stream.Guid); }
public async Task SendPacket(MOMsg packet) { if (packet.ActionId == 100000) { //登录绑定 _user = GrainFactory.GetGrain <IUserGrain>(packet.UserId); await _globalWorld.PlayerEnterGlobalWorld(_user); if (_curRoom != null) { await _curRoom.Reconnect(_user); //通知上线 var message = new MOMsg() { ActionId = 100, Content = new S2C100() { UserId = _user.GetPrimaryKeyLong(), IsOnline = true }.ToByteString() }; await _curRoom.RoomNotify(message); } await _user.Notify(packet.ParseResult()); } else { if (_user == null) { await _user.Notify(packet.ParseResult(MOErrorType.Hidden, "用户未登录")); return; } if (packet.ActionId == 100001) { var req = C2S100001.Parser.ParseFrom(packet.Content); if (_curRoom == null) { _curRoom = GrainFactory.GetGrain <IRoomGrain>(req.RoomId); } await _curRoom.PlayerEnterRoom(_user); } else { if (_curRoom == null) { await _user.Notify(packet.ParseResult(MOErrorType.Hidden, "房间信息不存在")); return; } switch (packet.ActionId) { case 100005: { await _curRoom.PlayerLeaveRoom(_user); _curRoom = null; } break; case 100007: { var req = C2S100007.Parser.ParseFrom(packet.Content); await _curRoom.PlayerSendMsg(_user, req.Content); } break; case 100009: { var req = C2S100009.Parser.ParseFrom(packet.Content); await _curRoom.PlayerCommand(_user, req.Commands.ToList()); } break; } } } }
public Task PlayerReady(IUserGrain user) { return(Task.CompletedTask); }
public async Task PlayerLeaveGlobalWorld(IUserGrain user) { _userDict.Remove(user.GetPrimaryKeyLong()); await user.UnsubscribeGlobal(); }
public async Task PlayerEnterGlobalWorld(IUserGrain user) { _userDict[user.GetPrimaryKeyLong()] = user; await user.SubscribeGlobal(_stream.Guid); }
public async Task DispatchIncomingPacket(MOMsg packet) { try { //System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch(); //watch.Restart(); //md5签名验证 var sign = packet.Sign; packet.Sign = string.Empty; var data = packet.ToByteString(); if (CryptoHelper.MD5_Encrypt($"{data}{_md5Key}").ToLower() != sign.ToLower()) { await DispatchOutcomingPacket(packet.ParseResult(MOErrorType.Hidden, "签名验证失败")); await Close(); return; } //同步初始化 if (!_IsInit) { _tokenGrain = _client.GetGrain <ITokenGrain>(packet.UserId); var tokenInfo = _tokenGrain.GetToken().Result; if (tokenInfo.Token != packet.Token || tokenInfo.LastTime.AddSeconds(GameConstants.TOKENEXPIRE) < DateTime.Now) { await DispatchOutcomingPacket(packet.ParseResult(MOErrorType.Hidden, "Token验证失败")); await Close(); return; } _userId = packet.UserId; //_token = tokenInfo.Token; _packetObserver = new OutcomingPacketObserver(this); _router = _client.GetGrain <IPacketRouterGrain>(_userId); _user = _client.GetGrain <IUserGrain>(_userId); _packetObserverRef = _client.CreateObjectReference <IPacketObserver>(_packetObserver).Result; _user.BindPacketObserver(_packetObserverRef).Wait(); _IsInit = true; } else { //if (_userId != packet.UserId || _token != packet.Token) //{ // await DispatchOutcomingPacket(packet.ParseResult(MOErrorType.Hidden, "Token验证失败")); // await Close(); // return; //} var tokenInfo = _tokenGrain.GetToken().Result; if (tokenInfo.Token != packet.Token || tokenInfo.LastTime.AddSeconds(GameConstants.TOKENEXPIRE) < DateTime.Now) { await DispatchOutcomingPacket(packet.ParseResult(MOErrorType.Hidden, "Token验证失败")); await Close(); return; } } //心跳包 if (packet.ActionId == 1) { await _tokenGrain.RefreshTokenTime(); await DispatchOutcomingPacket(packet.ParseResult()); return; } await _router.SendPacket(packet); //watch.Stop(); //Console.WriteLine($"{packet.UserId} {watch.ElapsedMilliseconds}ms"); } catch (Exception ex) { _logger.LogError( $"DispatchIncomingPacket异常:\n" + $"{ex.Message}\n" + $"{ex.StackTrace}\n" + $"{JsonConvert.SerializeObject(packet)}"); } }
public async Task AddUser(IUserGrain user) { State.Users.Add(user); await WriteStateAsync(); }
public async Task <PaymentStatus> Pay(IUserGrain user, decimal amount) { return(State.Status = await user.ModifyCredit(-1 *amount) ? PaymentStatus.Paid : PaymentStatus.Pending); }
public async Task RemoveUser(IUserGrain user) { State.Users.Remove(user); await WriteStateAsync(); }
public async Task <bool> SetUser(IUserGrain userGrain) { State.UserId = userGrain.GetPrimaryKey(); return(true); }