private void ExecuteEvents(object ex = null) { var dict = new Dictionary<string, string>(); foreach(var i in _dataProviders) { var results = i.AfterEvent(); if(results != null) { foreach(var j in results) { dict[j.Key] = j.Value; } } } var eventContext = new EventContext(dict) { Name = _eventMetadata.Name, Exception = ex }; foreach(var i in _eventHandlers) { i.OnEvent(eventContext); } }
void OnKeyDown(EventContext context) { if (context.inputEvent.keyCode == KeyCode.Escape) { Application.Quit(); } }
public void ChangingAnEventDisconnectedDoesNotCreateDuplicates() { Event e; using (var context = new EventContext()) { var eventUoW = new EventUnitOfWork(context); e = new Event(); e.Brief = "Test"; e.Detailed = "Test"; e.ModificationState = ModificationState.Added; e.AppUser = context.Users.Single(t => t.UserName == "TestUser"); eventUoW.Events.Attach(e); eventUoW.Save(); } e.Brief = "MyBrief"; e.Detailed = "MyDetailed"; e.ModificationState = ModificationState.Modified; using (var context = new EventContext()) { var eventUoW = new EventUnitOfWork(context); eventUoW.Events.Attach(e); eventUoW.Save(); } using (var context = new EventContext()) { context.Invoking(t => t.Events.Single()).ShouldNotThrow(); } }
public double EvaluateOnTold(Character perspectiveCharacter, Character evaluateCharacter, Game game) { //The perspectiveCharacter is the character performing the query. //The evaluateCharacter is the character whose opinion on the information we care about. EventContext observeContext = new EventContext(evaluateCharacter, parameters); return information.OnTold.Evaluate(game, observeContext, evaluateCharacter.GetWeights(perspectiveCharacter)); }
void OnClickList(EventContext context) { //find out if there is an item in edit status //查找是否有项目处于编辑状态 int cnt = _list.numChildren; for (int i = 0; i < cnt; i++) { GButton item = _list.GetChildAt(i).asButton; if (item.scrollPane.posX != 0) { //Check if clicked on the button if (item.GetChild("b0").asButton.IsAncestorOf(GRoot.inst.touchTarget) || item.GetChild("b1").asButton.IsAncestorOf(GRoot.inst.touchTarget)) { return; } item.scrollPane.SetPosX(0, true); //avoid scroll pane default behavior //取消滚动面板可能发生的拉动。 item.scrollPane.CancelDragging(); _list.scrollPane.CancelDragging(); break; } } }
public override void EventProcessing(EventContext context) { if (Settings.Current.WebsiteMode == WebsiteMode.Dev) return; // Throttle errors by client ip address to no more than X every 5 minutes. var ri = context.Event.GetRequestInfo(); if (ri == null || String.IsNullOrEmpty(ri.ClientIpAddress)) return; string throttleCacheKey = String.Concat("bot:", ri.ClientIpAddress, ":", DateTime.Now.Floor(_throttlingPeriod).Ticks); var requestCount = _cacheClient.Get<int?>(throttleCacheKey); if (requestCount != null) { _cacheClient.Increment(throttleCacheKey, 1); requestCount++; } else { _cacheClient.Set(throttleCacheKey, 1, _throttlingPeriod); requestCount = 1; } if (requestCount < Settings.Current.BotThrottleLimit) return; Log.Info().Message("Bot throttle triggered. IP: {0} Time: {1} Project: {2}", ri.ClientIpAddress, DateTime.Now.Floor(_throttlingPeriod), context.Event.ProjectId).Project(context.Event.ProjectId).Write(); // the throttle was triggered, go and delete all the errors that triggered the throttle to reduce bot noise in the system Task.Run(() => _eventRepository.RemoveAllByClientIpAndDateAsync(ri.ClientIpAddress, DateTime.Now.Floor(_throttlingPeriod), DateTime.Now.Ceiling(_throttlingPeriod))); context.IsCancelled = true; }
void OnRotate(EventContext context) { DOTween.Kill(_ball); RotationGesture gesture = (RotationGesture)context.sender; _ball.Rotate(Vector3.forward, -gesture.delta, Space.World); }
public EventUnitOfWork(EventContext context) { this.context = context; Events = new EventRepository(context); Users = new UserRepository(context, new UserManager<AppUser, string>(new UserStore<AppUser>(context))); Invites = new InviteRepository(context); InviteLinks = new InviteLinkRepository(context); }
/// <summary> /// Constructor /// </summary> /// <param name="listener"></param> /// <param name="data"></param> public AsyncLocalNotifyUpdateCallback(ICacheEventsListener listener, object key, object entry, OperationContext operationContext, EventContext eventContext) { _listener = listener; _key = key; _entry = entry; _operationContext = operationContext; _eventContext = eventContext; }
void OnPinch(EventContext context) { DOTween.Kill(_ball); FairyGUI.PinchGesture gesture = (FairyGUI.PinchGesture)context.sender; float newValue = Mathf.Clamp(_ball.localScale.x + gesture.delta, 0.3f, 2); _ball.localScale = new Vector3(newValue, newValue, newValue); }
public bool Evaluate(EventContext context, Game game) { for(int i = 0; i < subexpressions.Length; ++i) { if (!subexpressions[i].Evaluate(context, game)) return false; } return true; }
/// <summary> /// Constructor /// </summary> /// <param name="listener"></param> /// <param name="data"></param> public AsyncBroadcastCustomNotifyRemoval(ClusterCacheBase parent, object key, CacheEntry entry, ItemRemoveReason reason, OperationContext operationContext, EventContext eventContext) { _parent = parent; _key = key; _entry = entry; _reason = reason; _operationContext = operationContext; _eventContext = eventContext; }
void __joystickMove(EventContext context) { float degree = (float)context.data; //-90:up 0:right 90:down 180/-180:left if (degree > -90 && degree < 90) //right _npc.Translate(0.01f, 0, 0, Space.World); else _npc.Translate(-0.01f, 0, 0, Space.World); }
public double Calculate(EventContext context, Game game) { double result = 0.0; foreach(var part in parts) { result += part.Calculate(context, game); } return result; }
public static void Initialize(TestContext testContext) { var context = new EventContext(); context.Database.Delete(); var configuration = new TestMigrationConfiguration(); var migrator = new DbMigrator(configuration); migrator.Update(); }
public CalendarViewModel() { _eventContext = ContextFactory.GetEventContext(); _teamContext = ContextFactory.GetTeamContext(); _currentDate = DateTime.Now; _deleteCommand = new RelayCommand(OnDelete); AppMessages.EventAddedMessage.Register(this, OnEventAdded); IsLoggedIn = true; LoadData(); }
public virtual void ProcessEvent(EventContext context, Action continueProcessing) { if (EventContext.Directions.In == context.Direction) { this.ProcessInbound(context, continueProcessing); } if (EventContext.Directions.Out == context.Direction) { this.ProcessOutbound(context, continueProcessing); } }
public void should_return_username() { using( var context = new EventContext()) { var eventUoW = new EventUnitOfWork(context); var user = eventUoW.Users.GetUserByUsername("Lars"); user.Should().NotBeNull(); user.UserName.Should().Be("Lars"); } }
public void username_should_be_null() { using(var context = new EventContext()) { var eventUoW = new EventUnitOfWork(context); var user = eventUoW.Users.GetUserByUsername("Laurene"); user.Should().BeNull(); } }
public override void Process(EventContext ctx) { _publisher.PublishAsync(new EventOccurrence { Id = ctx.Event.Id, OrganizationId = ctx.Event.OrganizationId, ProjectId = ctx.Event.ProjectId, StackId = ctx.Event.StackId, IsHidden = ctx.Event.IsHidden, IsFixed = ctx.Event.IsFixed, IsNotFound = ctx.Event.IsNotFound(), IsRegression = ctx.IsRegression }); }
protected UsingSagaEventHandlerBase() { var executor = new Action<Object, Event>((handler, e) => { ((FakeSaga)handler).Handle((FakeEvent)e); Handled = true; }); SagaId = GuidStrategy.NewGuid(); AggregateId = GuidStrategy.NewGuid(); Event = new FakeEvent { Id = SagaId }; SagaMetadata = new FakeSaga().GetMetadata(); EventContext = new EventContext(AggregateId, HeaderCollection.Empty, Event); EventHandler = new EventHandler(typeof(FakeSaga), typeof(FakeEvent), executor, () => { throw new NotSupportedException(); }); SagaEventHandler = new SagaEventHandler(EventHandler, SagaMetadata, SagaStore.Object, new Lazy<IPublishCommands>(() => CommandPublisher.Object)); }
public void InvokeUnderlyingExecutorWithEventAndHandlerInstance() { var handled = false; var e = new FakeEvent(); var handler = new Object(); var eventHandler = new EventHandler(typeof(Object), typeof(FakeEvent), (a, b) => { handled = a == handler && b == e; }, () => handler); using (var context = new EventContext(GuidStrategy.NewGuid(), HeaderCollection.Empty, e)) eventHandler.Handle(context); Assert.True(handled); }
//ctor public EventViewModel() { _saveChangesCommand = new RelayCommand( OnSaveChanges ); _context = ContextFactory.GetEventContext(); _teamContext = ContextFactory.GetTeamContext(); _eventTeamContext = ContextFactory.GetEventTeamContext(); WebContext.Current.Authentication.LoggedIn += ( s, e ) => UpdateForUsersRole(); WebContext.Current.Authentication.LoggedOut += ( s, e ) => UpdateForUsersRole(); UpdateForUsersRole(); LoadTeams(); }
public void CurrentContextSetToNewEventContextInstance() { var @event = new FakeEvent(); var aggregateId = Guid.NewGuid(); using (var context = new EventContext(aggregateId, HeaderCollection.Empty, @event)) { Assert.Same(context, EventContext.Current); Assert.Same(@event, EventContext.Current.Event); Assert.Equal(aggregateId, EventContext.Current.AggregateId); Assert.Equal(HeaderCollection.Empty, EventContext.Current.Headers); } }
public static void ClassCleanup() { // Since users are not cleaned up by transactions (why is this?), we need to clear the state // after these tests have been run. using (var context = new EventContext()) { context.Database.Delete(); var configuration = new TestMigrationConfiguration(); var migrator = new DbMigrator(configuration); migrator.Update(); } }
public ReservationsViewModel() { _eventContext = ContextFactory.GetEventContext(); _ticketContext = ContextFactory.GetTicketContext(); IsLoggedIn = true; AppMessages.TicketAddedMessage.Register(this, OnTicketAdded); LoadData(); _deleteCommand = new RelayCommand(OnDelete); _searchEventsCommand = new RelayCommand(OnSearchEvents); _editCommand = new RelayCommand(OnEdit); }
/// <summary> /// Invokes the underlying <see cref="Saga"/> event handler method using the specified event <paramref name="context"/>. /// </summary> /// <param name="context">The current event context.</param> public override void Handle(EventContext context) { Verify.NotNull(context, nameof(context)); var sagaId = sagaMetadata.GetCorrelationId(context.Event); using (var sagaContext = new SagaContext(HandlerType, sagaId, context.Event)) { Handle(sagaContext); var commandPublisher = lazyCommandPublisher.Value; foreach (var sagaCommand in sagaContext.GetPublishedCommands()) commandPublisher.Publish(sagaCommand.AggregateId, sagaCommand.Command, sagaCommand.Headers); } }
public void GetChangedModifiers(EventContext context, Game game, List<PrestigeModifier> added, List<PrestigeModifier> removed) { foreach (var modifier in prestigeModifiers) { if (modifier.EvaluateRequirements(context, game) && !modifier.EvaluateRequirements(context.CurrentCharacter, game)) { added.Add(modifier); } else if (!modifier.EvaluateRequirements(context, game) && modifier.EvaluateRequirements(context.CurrentCharacter, game)) { removed.Add(modifier); } } }
public override void Process(EventContext ctx) { if (ctx.StackInfo == null || !ctx.StackInfo.DateFixed.HasValue || ctx.StackInfo.DateFixed.Value >= ctx.Event.Date.UtcDateTime) return; Log.Trace().Message("Marking event as an regression.").Write(); _stackRepository.MarkAsRegressed(ctx.StackInfo.Id); _eventRepository.MarkAsRegressedByStack(ctx.StackInfo.Id); string signatureHash = ctx.GetProperty<string>("__SignatureHash"); _stackRepository.InvalidateCache(ctx.Event.StackId, signatureHash, ctx.Event.ProjectId); ctx.Event.IsFixed = false; ctx.IsRegression = true; }
public void GetInvitedToEventReturnsOnlyPeopleInvitedToAnEvent() { using (var context = new EventContext()) { var eventUoW = new EventUnitOfWork(context); var userManager = new UserManager<AppUser>(new UserStore<AppUser>(context)); var user1 = context.Users.Single(t => t.UserName == "TestUser"); var user2 = context.Users.Single(t => t.UserName == "TestUser2"); var user3 = context.Users.Single(t => t.UserName == "TestUser3"); Event e1 = new Event(); e1.Brief = "User 1 Event"; e1.Visibility = EventVisibility.Private; e1.ModificationState = ModificationState.Added; e1.AppUser = user1; eventUoW.Events.Attach(e1); Invite i1 = new Invite(); i1.AppUser = user2; i1.Event = e1; i1.ModificationState = ModificationState.Added; eventUoW.Invites.Attach(i1); Invite i2 = new Invite(); i2.AppUser = user3; i2.Event = e1; i2.ModificationState = ModificationState.Added; eventUoW.Invites.Attach(i2); eventUoW.Save(); } using (var context = new EventContext()) { var eventUoW = new EventUnitOfWork(context); var userManager = new UserManager<AppUser>(new UserStore<AppUser>(context)); var e1 = context.Events.Single(t => t.Brief == "User 1 Event"); var user1 = context.Users.Single(t => t.UserName == "TestUser"); var user2 = context.Users.Single(t => t.UserName == "TestUser2"); var user3 = context.Users.Single(t => t.UserName == "TestUser3"); var invited = eventUoW.Invites.GetInvitedToEvent(e1); invited.Should().HaveCount(2); invited.Any(t => t.AppUser == null).Should().BeFalse(); invited.Any(t => t.AppUser == user1).Should().BeFalse(); invited.Any(t => t.AppUser == user2).Should().BeTrue(); invited.Any(t => t.AppUser == user3).Should().BeTrue(); } }
/// Internal for testing purposes internal Task UpdateSettings(SqlToolsSettings newSettings, SqlToolsSettings oldSettings, EventContext eventContext) { Settings.QueryExecutionSettings.Update(newSettings.QueryExecutionSettings); return(Task.FromResult(0)); }
/// <summary> /// Constructor /// </summary> /// <param name="listener"></param> /// <param name="data"></param> public AsyncBroadcastCustomNotifyRemoval(ClusterCacheBase parent, object key, CacheEntry entry, ItemRemoveReason reason, OperationContext operationContext, EventContext eventContext) { _parent = parent; _key = key; _entry = entry; _reason = reason; _operationContext = operationContext; _eventContext = eventContext; }
private void OnClickMap(EventContext context) { WinCenter.inst.TransView <UIAdventureView>(); }
public override Task ProcessAsync(EventContext ctx) { return(Task.CompletedTask); }
private void OnClickBag(EventContext context) { WinCenter.inst.TransView <UIBagView>(); }
public EventTypeController(EventContext eventTypeContext) { _eventTypeContext = eventTypeContext; }
public override void SetParent(EventContext parent, EventPath path) { base.SetParent(parent, path); }
public Task Handle(MyFirstEvent @event, EventContext context, string extra) => Task.CompletedTask;
private void __clickMenu(EventContext context) { GObject itemObject = (GObject)context.data; UnityEngine.Debug.Log("click " + itemObject.text); }
public async Task IAmListAsync(EventContext e) { using (var context = new MikiContext()) { int page = Math.Max((e.Arguments.Join()?.TakeInt() ?? 0) - 1, 0); long guildId = e.Guild.Id.ToDbLong(); List <LevelRole> roles = await context.LevelRoles .Where(x => x.GuildId == guildId) .OrderBy(x => x.RoleId) .Skip(page * 25) .Take(25) .ToListAsync(); StringBuilder stringBuilder = new StringBuilder(); var guildRoles = await e.Guild.GetRolesAsync(); List <Tuple <IDiscordRole, LevelRole> > availableRoles = roles .Where(x => guildRoles.Any(y => x.RoleId == (long)y.Id)) .Select(x => new Tuple <IDiscordRole, LevelRole>(guildRoles .Single(y => x.RoleId == (long)y.Id), x) ).ToList(); foreach (var role in availableRoles) { if (role.Item2.Optable) { if (role.Item1 == null) { context.LevelRoles.Remove(role.Item2); continue; } stringBuilder.Append($"`{role.Item1.Name.PadRight(20)}|`"); if (role.Item2.RequiredLevel > 0) { stringBuilder.Append($"⭐{role.Item2.RequiredLevel} "); } if (role.Item2.Automatic) { stringBuilder.Append($"⚙️"); } if (role.Item2.RequiredRole != 0) { var roleRequired = await e.Guild.GetRoleAsync(role.Item2.RequiredRole.FromDbLong()); stringBuilder.Append($"🔨`{roleRequired?.Name ?? "non-existing role"}`"); } if (role.Item2.Price != 0) { stringBuilder.Append($"🔸{role.Item2.Price} "); } stringBuilder.AppendLine(); } } if (stringBuilder.Length == 0) { stringBuilder.Append(e.Locale.GetString("miki_placeholder_null")); } await context.SaveChangesAsync(); new EmbedBuilder().SetTitle("📄 Available Roles") .SetDescription(stringBuilder.ToString()) .SetColor(204, 214, 221) .SetFooter("page " + (page + 1)) .ToEmbed().QueueToChannel(e.Channel); } }
private async Task UpdateGeoInformationAsync(EventContext context, IEnumerable <string> ips) { var result = await GetGeoFromIpAddressesAsync(ips).AnyContext(); UpdateGeoAndLocation(context.Event, result); }
private void OnClickShangPu(EventContext context) { OnClickBuilding(EBuilding.ShangPu); }
public async Task IAmAsync(EventContext e) { using (var context = new MikiContext()) { string roleName = e.Arguments.ToString(); List <IDiscordRole> roles = await GetRolesByName(e.Guild, roleName); IDiscordRole role = null; if (roles.Count > 1) { List <LevelRole> levelRoles = await context.LevelRoles.Where(x => x.GuildId == (long)e.Guild.Id).ToListAsync(); if (levelRoles.Where(x => x.GetRoleAsync().Result.Name.ToLower() == roleName.ToLower()).Count() > 1) { e.ErrorEmbed("two roles configured have the same name.") .ToEmbed().QueueToChannel(e.Channel); return; } else { role = levelRoles.Where(x => x.GetRoleAsync().Result.Name.ToLower() == roleName.ToLower()).FirstOrDefault().GetRoleAsync().Result; } } else { role = roles.FirstOrDefault(); } if (role == null) { e.ErrorEmbedResource("error_role_null") .ToEmbed().QueueToChannel(e.Channel); return; } IDiscordGuildUser author = await e.Guild.GetMemberAsync(e.Author.Id); if (author.RoleIds.Contains(role.Id)) { e.ErrorEmbed(e.Locale.GetString("error_role_already_given")) .ToEmbed().QueueToChannel(e.Channel); return; } LevelRole newRole = await context.LevelRoles.FindAsync(e.Guild.Id.ToDbLong(), role.Id.ToDbLong()); User user = (await context.Users.FindAsync(e.Author.Id.ToDbLong())); IDiscordGuildUser discordUser = await e.Guild.GetMemberAsync(user.Id.FromDbLong()); LocalExperience localUser = await LocalExperience.GetAsync(context, e.Guild.Id.ToDbLong(), discordUser.Id.ToDbLong(), discordUser.Username); if (!newRole?.Optable ?? false) { await e.ErrorEmbed(e.Locale.GetString("error_role_forbidden")) .ToEmbed().SendToChannel(e.Channel); return; } int level = User.CalculateLevel(localUser.Experience); if (newRole.RequiredLevel > level) { await e.ErrorEmbed(e.Locale.GetString("error_role_level_low", newRole.RequiredLevel - level)) .ToEmbed().SendToChannel(e.Channel); return; } if (newRole.RequiredRole != 0 && !discordUser.RoleIds.Contains(newRole.RequiredRole.FromDbLong())) { var requiredRole = await e.Guild.GetRoleAsync(newRole.RequiredRole.FromDbLong()); e.ErrorEmbed( e.Locale.GetString( "error_role_required", $"**{requiredRole.Name}**" ) ).ToEmbed().QueueToChannel(e.Channel); return; } if (newRole.Price > 0) { if (user.Currency >= newRole.Price) { await user.AddCurrencyAsync(-newRole.Price); await context.SaveChangesAsync(); } else { await e.ErrorEmbed(e.Locale.GetString("user_error_insufficient_mekos")) .ToEmbed().SendToChannel(e.Channel); return; } } var me = await e.Guild.GetSelfAsync(); if (!await me.HasPermissionsAsync(GuildPermission.ManageRoles)) { e.ErrorEmbed(e.Locale.GetString("permission_error_low", "give roles")).ToEmbed() .QueueToChannel(e.Channel); return; } if (newRole.GetRoleAsync().Result.Position >= await me.GetHierarchyAsync()) { e.ErrorEmbed(e.Locale.GetString("permission_error_low", "give roles")).ToEmbed() .QueueToChannel(e.Channel); return; } await author.AddRoleAsync(newRole.GetRoleAsync().Result); new EmbedBuilder() .SetTitle("I AM") .SetColor(128, 255, 128) .SetDescription($"You're a(n) {role.Name} now!") .ToEmbed().QueueToChannel(e.Channel); } }
public void Should_process_a_query_with_modifiers() { var expectedCommand = new BsonDocument { { "find", MessageHelper.DefaultCollectionNamespace.CollectionName }, { "projection", new BsonDocument("b", 1) }, { "skip", 1 }, { "batchSize", 2 }, { "limit", 100 }, { "awaitData", true }, { "noCursorTimeout", true }, { "allowPartialResults", true }, { "tailable", true }, { "oplogReplay", true }, { "filter", new BsonDocument("x", 1) }, { "sort", new BsonDocument("a", -1) }, { "comment", "funny" }, { "maxTimeMS", 20 }, { "showRecordId", true }, }; var expectedReplyDocuments = new[] { new BsonDocument("first", 1), new BsonDocument("second", 2) }; var expectedReply = new BsonDocument { { "cursor", new BsonDocument { { "id", 20L }, { "ns", MessageHelper.DefaultCollectionNamespace.FullName }, { "firstBatch", new BsonArray(expectedReplyDocuments) } } }, { "ok", 1 } }; var query = new BsonDocument { { "$query", expectedCommand["filter"] }, { "$orderby", expectedCommand["sort"] }, { "$comment", expectedCommand["comment"] }, { "$maxTimeMS", expectedCommand["maxTimeMS"] }, { "$showDiskLoc", expectedCommand["showRecordId"] }, }; var requestMessage = MessageHelper.BuildQuery( query, fields: (BsonDocument)expectedCommand["projection"], requestId: 10, skip: expectedCommand["skip"].ToInt32(), batchSize: expectedCommand["batchSize"].ToInt32(), noCursorTimeout: expectedCommand["noCursorTimeout"].ToBoolean(), awaitData: expectedCommand["awaitData"].ToBoolean(), partialOk: expectedCommand["allowPartialResults"].ToBoolean(), tailableCursor: expectedCommand["tailable"].ToBoolean(), oplogReplay: expectedCommand["oplogReplay"].ToBoolean()); using (EventContext.BeginFind(expectedCommand["batchSize"].ToInt32(), expectedCommand["limit"].ToInt32())) { SendMessages(requestMessage); } var replyMessage = MessageHelper.BuildReply <BsonDocument>( expectedReplyDocuments, BsonDocumentSerializer.Instance, responseTo: requestMessage.RequestId, cursorId: expectedReply["cursor"]["id"].ToInt64()); ReceiveMessages(replyMessage); var commandStartedEvent = (CommandStartedEvent)_capturedEvents.Next(); var commandSucceededEvent = (CommandSucceededEvent)_capturedEvents.Next(); commandStartedEvent.CommandName.Should().Be(expectedCommand.GetElement(0).Name); commandStartedEvent.Command.Should().Be(expectedCommand); commandStartedEvent.ConnectionId.Should().Be(_subject.ConnectionId); commandStartedEvent.DatabaseNamespace.Should().Be(MessageHelper.DefaultDatabaseNamespace); commandStartedEvent.OperationId.Should().Be(EventContext.OperationId); commandStartedEvent.RequestId.Should().Be(requestMessage.RequestId); commandSucceededEvent.CommandName.Should().Be(commandStartedEvent.CommandName); commandSucceededEvent.ConnectionId.Should().Be(commandStartedEvent.ConnectionId); commandSucceededEvent.Duration.Should().BeGreaterThan(TimeSpan.Zero); commandSucceededEvent.OperationId.Should().Be(commandStartedEvent.OperationId); commandSucceededEvent.Reply.Should().Be(expectedReply); commandSucceededEvent.RequestId.Should().Be(commandStartedEvent.RequestId); }
private void OnClickNotOpen(EventContext context) { WinCenter.inst.ShowTips("功能未开放"); }
private void OnClickWaiGongFang(EventContext context) { OnClickBuilding(EBuilding.WaiGongFang); }
public override Task ProcessAsync(EventContext ctx) { return(TaskHelper.Completed()); }
public virtual void StopRepush(EventContext context) { this.IsDone = true; m_forceStoped = true; this.OnForceStoped?.Invoke(context); }
private void OnClickZhengDian(EventContext context) { WinCenter.inst.ShowPanel <UIBuildingLevelUp>((int)EBuilding.ZhengDian); }
public UserController(EventContext eventContext) { _eventContext = eventContext; }
void __clickItem(EventContext context) { }
private void OnClickResetData(EventContext context) { AppFacade.getInstance().DataReset(); }
public async Task IAmNotAsync(EventContext e) { string roleName = e.Arguments.ToString(); using (var context = new MikiContext()) { List <IDiscordRole> roles = await GetRolesByName(e.Guild, roleName); IDiscordRole role = null; if (roles.Count > 1) { List <LevelRole> levelRoles = await context.LevelRoles.Where(x => x.GuildId == (long)e.Guild.Id).ToListAsync(); if (levelRoles.Where(x => x.GetRoleAsync().Result.Name.ToLower() == roleName.ToLower()).Count() > 1) { e.ErrorEmbed("two roles configured have the same name.") .ToEmbed().QueueToChannel(e.Channel); return; } else { role = levelRoles.Where(x => x.GetRoleAsync().Result.Name.ToLower() == roleName.ToLower()).FirstOrDefault().GetRoleAsync().Result; } } else { role = roles.FirstOrDefault(); } if (role == null) { await e.ErrorEmbed(e.Locale.GetString("error_role_null")) .ToEmbed().SendToChannel(e.Channel); return; } IDiscordGuildUser author = await e.Guild.GetMemberAsync(e.Author.Id); IDiscordGuildUser me = await e.Guild.GetSelfAsync(); if (!author.RoleIds.Contains(role.Id)) { await e.ErrorEmbed(e.Locale.GetString("error_role_forbidden")) .ToEmbed().SendToChannel(e.Channel); return; } LevelRole newRole = await context.LevelRoles.FindAsync(e.Guild.Id.ToDbLong(), role.Id.ToDbLong()); User user = await context.Users.FindAsync(e.Author.Id.ToDbLong()); if (!await me.HasPermissionsAsync(GuildPermission.ManageRoles)) { e.ErrorEmbed(e.Locale.GetString("permission_error_low", "give roles")).ToEmbed() .QueueToChannel(e.Channel); return; } if ((await newRole.GetRoleAsync()).Position >= await me.GetHierarchyAsync()) { e.ErrorEmbed(e.Locale.GetString("permission_error_low", "give roles")).ToEmbed() .QueueToChannel(e.Channel); return; } await author.RemoveRoleAsync(newRole.GetRoleAsync().Result); new EmbedBuilder() .SetTitle("I AM NOT") .SetColor(255, 128, 128) .SetDescription($"You're no longer a(n) {role.Name}!") .ToEmbed().QueueToChannel(e.Channel); } }
public OptionsCreated(string name, EventContext context, EventData data) : base(name, context, data) { }
public async Task OverwatchStatsAsync(EventContext e) { string[] arguments = e.arguments.Split(' '); string[] username = arguments .Where(x => x.Contains("#")) .FirstOrDefault() .Split('#'); string[] toggles = arguments .Where(x => x.StartsWith("-")) .ToArray(); OverwatchUserResponse user = await InternalGetUser(e, username); if (user.Request != null) { bool competitive = toggles.Contains("-c"); OverwatchRegion region; if (toggles.Contains("-eu")) { region = user.Europe; } else if (toggles.Contains("-us")) { region = user.America; } else if (toggles.Contains("-kr")) { region = user.Korea; } else { region = GetBestRegion(user, competitive); } OverwatchUserContext c = new OverwatchUserContext(competitive, region); if (!c.isValid) { await e.ErrorEmbed("The user specified does not exist, or hasn't played on this specific region.") .SendToChannel(e.Channel); return; } IDiscordEmbed embed = Utils.Embed .SetTitle(string.Join("#", username) + "'s Overwatch Profile") .SetThumbnailUrl(c.Stats.OverallStats.avatar); var orderedPlaytime = c.PlayTime.OrderByDescending(x => x.Value); float seconds = orderedPlaytime.First().Value.FromHoursToSeconds(); if (c.isCompetitive) { embed.AddInlineField("MMR", c.Stats.OverallStats.tier.ToString() + " (" + c.Stats.OverallStats.comprank.ToString() + ")") .AddInlineField("Winrate", (c.Stats.OverallStats.win_rate) + "%"); } embed.AddInlineField("Favourite Character", orderedPlaytime.First().Key + " with " + Utils.ToTimeString(seconds, e.Channel.GetLocale())) .AddInlineField("K/D/A ratio", Math.Round(c.Stats.GameStats.eliminations / c.Stats.GameStats.deaths, 2)) .AddInlineField("Time Played", c.Stats.GameStats.time_played + " hours") .AddInlineField("Objective Time", c.Stats.GameStats.objective_time.FromHoursToSeconds().ToTimeString(e.Channel.GetLocale(), true)); await embed.SendToChannel(e.Channel); } else { await e.ErrorEmbed("The user specified does not exist!") .SendToChannel(e.Channel); return; } }
/*public async Task ConfigRoleInteractiveAsync(EventContext e) * { * using (var context = new MikiContext()) * { * EmbedBuilder sourceEmbed = Utils.Embed.SetTitle("⚙ Interactive Mode") * .SetDescription("Type out the role name you want to config") * .SetColor(138, 182, 239); * IDiscordMessage sourceMessage = await sourceEmbed.ToEmbed().SendToChannel(e.Channel); * IDiscordMessage msg = null; * * while (true) * { * msg = await e.EventSystem.GetCommandHandler<MessageListener>().WaitForNextMessage(e.CreateSession()); * * if (msg.Content.Length < 20) * { * break; * } * else * { * await sourceMessage.EditAsync(new EditMessageArgs * { * embed = e.ErrorEmbed("That role name is way too long! Try again.") * .ToEmbed() * }); * } * } * * string roleName = msg.Content; * * List<IDiscordRole> rolesFound = await GetRolesByName(e.Guild, roleName.ToLower()); * IDiscordRole role = null; * * if(rolesFound.Count == 0) * { * // Hey, I couldn't find this role, Can I make a new one? * await sourceMessage.EditAsync(new EditMessageArgs * { * embed = e.ErrorEmbed($"There's no role that is named `{roleName}`, Shall I create it? Y/N").ToEmbed() * }); * * msg = await e.EventSystem.GetCommandHandler<MessageListener>().WaitForNextMessage(e.CreateSession()); * * if (msg.Content.ToLower()[0] != 'y') * { * throw new RoleNullException(); * } * * role = await e.Guild.CreateRoleAsync(new CreateRoleArgs * { * Name = roleName, * }); * } * else if (rolesFound.Count > 1) * { * string roleIds = string.Join("\n", rolesFound.Select(x => $"`{x.Name}`: {x.Id}")); * * if (roleIds.Length > 1024) * { * roleIds = roleIds.Substring(0, 1024); * } * * sourceEmbed = Utils.Embed.SetTitle("⚙ Interactive Mode") * .SetDescription("I found multiple roles with that name, which one would you like? please enter the ID") * .AddInlineField("Roles - Ids", roleIds) * .SetColor(138, 182, 239); * * sourceMessage = await sourceEmbed.ToEmbed().SendToChannel(e.Channel); * while(true) * { * msg = await e.EventSystem.GetCommandHandler<MessageListener>().WaitForNextMessage(e.CreateSession()); * if (ulong.TryParse(msg.Content, out ulong id)) * { * role = rolesFound.Where(x => x.Id == id) * .FirstOrDefault(); * * if (role != null) * { * break; * } * else * { * await sourceMessage.EditAsync(new EditMessageArgs { * embed = e.ErrorEmbed("I couldn't find that role id in the list. Try again!") * .AddInlineField("Roles - Ids", string.Join("\n", roleIds)).ToEmbed() * }); * } * } * else * { * await sourceMessage.EditAsync(new EditMessageArgs * { * embed = e.ErrorEmbed("I couldn't find that role. Try again!") * .AddInlineField("Roles - Ids", string.Join("\n", roleIds)).ToEmbed() * }); * } * } * } * else * { * role = rolesFound.FirstOrDefault(); * } * * LevelRole newRole = await context.LevelRoles.FindAsync(e.Guild.Id.ToDbLong(), role.Id.ToDbLong()); * if(newRole == null) * { * newRole = (await context.LevelRoles.AddAsync(new LevelRole() * { * RoleId = role.Id.ToDbLong(), * GuildId = e.Guild.Id.ToDbLong() * })).Entity; * } * * sourceEmbed = Utils.Embed.SetTitle("⚙ Interactive Mode") * .SetDescription("Is there a role that is needed to get this role? Type out the role name, or `-` to skip") * .SetColor(138, 182, 239); * * sourceMessage = await sourceEmbed.ToEmbed().SendToChannel(e.Channel); * * while (true) * { * msg = await e.EventSystem.GetCommandHandler<MessageListener>().WaitForNextMessage(e.CreateSession()); * * rolesFound = (await GetRolesByName(e.Guild, msg.Content.ToLower())); * IDiscordRole parentRole = null; * * if (rolesFound.Count > 1) * { * string roleIds = string.Join("\n", rolesFound.Select(x => $"`{x.Name}`: {x.Id}")); * * if (roleIds.Length > 1024) * { * roleIds = roleIds.Substring(0, 1024); * } * * sourceEmbed = Utils.Embed.SetTitle("⚙ Interactive Mode") * .SetDescription("I found multiple roles with that name, which one would you like? please enter the ID") * .AddInlineField("Roles - Ids", roleIds) * .SetColor(138, 182, 239); * * sourceMessage = await sourceEmbed.ToEmbed().SendToChannel(e.Channel); * while (true) * { * msg = await e.EventSystem.GetCommandHandler<MessageListener>().WaitForNextMessage(e.CreateSession()); * if (ulong.TryParse(msg.Content, out ulong id)) * { * parentRole = rolesFound.Where(x => x.Id == id) * .FirstOrDefault(); * * if (parentRole != null) * { * break; * } * else * { * await sourceMessage.EditAsync(new EditMessageArgs { * embed = e.ErrorEmbed("I couldn't find that role id in the list. Try again!") * .AddInlineField("Roles - Ids", string.Join("\n", roleIds)).ToEmbed() * }) ; * } * } * else * { * await sourceMessage.EditAsync(new EditMessageArgs * { * embed = e.ErrorEmbed("I couldn't find that role. Try again!") * .AddInlineField("Roles - Ids", string.Join("\n", roleIds)).ToEmbed() * }); * } * } * } * else * { * parentRole = rolesFound.FirstOrDefault(); * } * * if (parentRole != null || msg.Content == "-") * { * newRole.RequiredRole = (long?)parentRole?.Id ?? 0; * break; * } * * await sourceMessage.EditAsync(new EditMessageArgs * { * embed = e.ErrorEmbed("I couldn't find that role. Try again!").ToEmbed() * }); * } * * sourceEmbed = Utils.Embed.SetTitle("⚙ Interactive Mode") * .SetDescription($"Is there a level requirement? type a number, if there is no requirement type 0") * .SetColor(138, 182, 239); * * sourceMessage = await sourceEmbed.ToEmbed().SendToChannel(e.Channel); * * while (true) * { * msg = await e.EventSystem.GetCommandHandler<MessageListener>().WaitForNextMessage(e.CreateSession()); * * if (int.TryParse(msg.Content, out int r)) * { * if (r >= 0) * { * newRole.RequiredLevel = r; * break; * } * else * { * await sourceMessage.EditAsync(new EditMessageArgs * { * embed = sourceEmbed.SetDescription($"Please pick a number above 0. Try again") * .ToEmbed() * }); * } * } * else * { * await sourceMessage.EditAsync(new EditMessageArgs * { * embed = sourceEmbed.SetDescription($"Are you sure `{msg.Content}` is a number? Try again").ToEmbed() * }); * } * } * * sourceEmbed = Utils.Embed.SetTitle("⚙ Interactive Mode") * .SetDescription($"Should I give them when the user level ups? type `yes`, otherwise it will be considered as no") * .SetColor(138, 182, 239); * * sourceMessage = await sourceEmbed.ToEmbed().SendToChannel(e.Channel); * * msg = await e.EventSystem.GetCommandHandler<MessageListener>().WaitForNextMessage(e.CreateSession()); * if (msg == null) * { * return; * } * * newRole.Automatic = msg.Content.ToLower()[0] == 'y'; * * sourceEmbed = Utils.Embed.SetTitle("⚙ Interactive Mode") * .SetDescription($"Should users be able to opt in? type `yes`, otherwise it will be considered as no") * .SetColor(138, 182, 239); * * sourceMessage = await sourceEmbed.ToEmbed().SendToChannel(e.Channel); * * msg = await e.EventSystem.GetCommandHandler<MessageListener>().WaitForNextMessage(e.CreateSession()); * * newRole.Optable = msg.Content.ToLower()[0] == 'y'; * * if (newRole.Optable) * { * sourceEmbed = Utils.Embed.SetTitle("⚙ Interactive Mode") * .SetDescription($"Do you want the user to pay mekos for the role? Enter any amount. Enter 0 to keep the role free.") * .SetColor(138, 182, 239); * * sourceMessage = await sourceEmbed.ToEmbed().SendToChannel(e.Channel); * * while (true) * { * msg = await e.EventSystem.GetCommandHandler<MessageListener>().WaitForNextMessage(e.CreateSession()); * * if (msg == null) * { * return; * } * * if (int.TryParse(msg.Content, out int r)) * { * if (r >= 0) * { * newRole.Price = r; * break; * } * else * { * await sourceMessage.EditAsync(new EditMessageArgs * { * embed = e.ErrorEmbed($"Please pick a number above 0. Try again").ToEmbed() * }); * } * } * else * { * await sourceMessage.EditAsync(new EditMessageArgs * { * embed = e.ErrorEmbed($"Not quite sure if this is a number 🤔").ToEmbed() * }); * } * } * } * * await context.SaveChangesAsync(); * Utils.Embed.SetTitle("⚙ Role Config") * .SetColor(102, 117, 127) * .SetDescription($"Updated {role.Name}!") * .ToEmbed().QueueToChannel(e.Channel); * } * }*/ public async Task ConfigRoleQuickAsync(EventContext e) { using (var context = new MikiContext()) { string roleName = e.Arguments.ToString().Split('"')[1]; IDiscordRole role = null; if (ulong.TryParse(roleName, out ulong s)) { role = await e.Guild.GetRoleAsync(s); } else { role = (await GetRolesByName(e.Guild, roleName)).FirstOrDefault(); } LevelRole newRole = await context.LevelRoles.FindAsync(e.Guild.Id.ToDbLong(), role.Id.ToDbLong()); MSLResponse arguments = new MMLParser(e.Arguments.ToString().Substring(roleName.Length + 3)) .Parse(); if (role.Name.Length > 20) { await e.ErrorEmbed("Please keep role names below 20 letters.") .ToEmbed().SendToChannel(e.Channel); return; } if (newRole == null) { newRole = context.LevelRoles.Add(new LevelRole() { GuildId = (e.Guild.Id.ToDbLong()), RoleId = (role.Id.ToDbLong()), }).Entity; } if (arguments.HasKey("automatic")) { newRole.Automatic = arguments.GetBool("automatic"); } if (arguments.HasKey("optable")) { newRole.Optable = arguments.GetBool("optable"); } if (arguments.HasKey("level-required")) { newRole.RequiredLevel = arguments.GetInt("level-required"); } if (arguments.HasKey("price")) { newRole.Price = arguments.GetInt("price"); } if (arguments.HasKey("role-required")) { long id = 0; if (arguments.TryGet("role-required", out long l)) { id = l; } else { var r = (await e.Guild.GetRolesAsync()) .Where(x => x.Name.ToLower() == arguments.GetString("role-required").ToLower()) .FirstOrDefault(); if (r != null) { id = r.Id.ToDbLong(); } } if (id != 0) { newRole.RequiredRole = id; } } await context.SaveChangesAsync(); new EmbedBuilder() .SetTitle("⚙ Role Config") .SetColor(102, 117, 127) .SetDescription($"Updated {role.Name}!") .ToEmbed().QueueToChannel(e.Channel); } }
/// <inheritdoc/> public override async Task <string> PublishAsync <TEvent>(EventContext <TEvent> @event, EventRegistration registration, DateTimeOffset?scheduled = null, CancellationToken cancellationToken = default) { using var scope = CreateScope(); using var ms = new MemoryStream(); await SerializeAsync(body : ms, @event : @event, registration : registration, scope : scope, cancellationToken : cancellationToken); var message = new ServiceBusMessage(ms.ToArray()) { MessageId = @event.Id, ContentType = @event.ContentType.ToString(), }; // If CorrelationId is present, set it if (@event.CorrelationId != null) { message.CorrelationId = @event.CorrelationId; } // If scheduled for later, set the value in the message if (scheduled != null && scheduled > DateTimeOffset.UtcNow) { message.ScheduledEnqueueTime = scheduled.Value.UtcDateTime; } // If expiry is set in the future, set the ttl in the message if (@event.Expires != null && @event.Expires > DateTimeOffset.UtcNow) { var ttl = @event.Expires.Value - DateTimeOffset.UtcNow; message.TimeToLive = ttl; } // Add custom properties message.ApplicationProperties.AddIfNotDefault(AttributeNames.RequestId, @event.RequestId) .AddIfNotDefault(AttributeNames.InitiatorId, @event.InitiatorId) .AddIfNotDefault(AttributeNames.ActivityId, Activity.Current?.Id); // Get the sender and send the message accordingly var sender = await GetSenderAsync(registration, cancellationToken); Logger.LogInformation("Sending {Id} to '{EntityPath}'. Scheduled: {Scheduled}", @event.Id, sender.EntityPath, scheduled); if (scheduled != null) { var seqNum = await sender.ScheduleMessageAsync(message : message, scheduledEnqueueTime : message.ScheduledEnqueueTime, cancellationToken : cancellationToken); return(seqNum.ToString()); // return the sequence number } else { await sender.SendMessageAsync(message, cancellationToken); return(null); // no sequence number available } }
/// <summary> /// 响应手牌点击事件的函数 /// </summary> public void OnClickHandCard(EventContext context) { // 如果不是玩家回合,则无法使用卡牌 if (!Gameplay.Instance().roundProcessController.IsPlayerRound()) { return; } // int index = _handcardList.GetChildIndex(context.data as GObject); // BaseCard baseCardReference = handcardInstanceList[index].GetComponent<BaseCard>(); // if (!Player.Instance().CanConsumeAp(baseCardReference.cost)) // { // Debug.Log("Ran out of AP, cant use this one"); // return; // } GObject item = context.data as GObject; // 确认当前点击的卡牌和上次点击的不同,此时表明用户想使用这张卡牌 if (item != lastClicked) { // 改变记录 lastClicked = item; // 动效 //DoSpecialEffect(item); // 设置当前选中的卡牌 CardManager.Instance().SetSelectingCard(_handcardList.GetChildIndex(item)); } else // 此时用户点击的牌和上次相同,表示用户想取消使用 { // 恢复原大小 foreach (GObject litem in _handcardList.GetChildren()) { StartCoroutine(FancyHandCardEffect(litem, 1)); } // 重置上次选择项 lastClicked = null; // 调用取消使用方法 CardManager.Instance().CancleUseCurrentCard(); // 结束函数执行,因为用户取消使用 return; } CardManager.Instance().OnUseCurrentCard(); // // 若是效果牌 // if (baseCardReference.type.Equals("Order")) // { //// // 判断使用结果 //// if (baseCardReference.Use()) //// { //// // 使用成功则移除手牌 //// CardManager.Instance().RemoveCardToCd(index); //// return; //// } // // baseCardReference.Use(); // // } // else // { // if (Gameplay.Instance().gamePlayInput.IsSelectingCard == false) // { // Gameplay.Instance().gamePlayInput. OnPointerDownUnitCard(handcardInstanceList[index]); // BattleMap.BattleMap.Instance().IsColor = true; // } // } }
public async Task GuildWeekly(EventContext context) { using (MikiContext database = new MikiContext()) { Locale locale = Locale.GetEntity(context.Channel.Id); LocalExperience thisUser = await database.Experience.FindAsync(context.Guild.Id.ToDbLong(), context.Author.Id.ToDbLong()); GuildUser thisGuild = await database.GuildUsers.FindAsync(context.Guild.Id.ToDbLong()); Timer timer = await database.Timers.FindAsync(context.Guild.Id.ToDbLong(), context.Author.Id.ToDbLong()); if (thisUser == null) { Log.ErrorAt("Guildweekly", "User is null"); return; } if (thisGuild == null) { Log.ErrorAt("Guildweekly", "Guild is null"); return; } if (thisUser.Experience > thisGuild.MinimalExperienceToGetRewards) { if (timer == null) { timer = database.Timers.Add(new Timer() { GuildId = context.Guild.Id.ToDbLong(), UserId = context.Author.Id.ToDbLong(), Value = DateTime.Now.AddDays(-30) }); await database.SaveChangesAsync(); } if (timer.Value.AddDays(7) <= DateTime.Now) { SocketGuild guild = Bot.instance.Client.GetGuild(thisGuild.Id.FromDbLong()); GuildUser rival = await thisGuild.GetRival(); if (rival == null) { await Utils.Embed .SetTitle(locale.GetString("miki_terms_weekly")) .SetDescription(context.GetResource("guildweekly_error_no_rival")) .SendToChannel(context.Channel); return; } if (rival.Experience > thisGuild.Experience) { await Utils.Embed .SetTitle(locale.GetString("miki_terms_weekly")) .SetDescription(context.GetResource("guildweekly_error_low_level")) .SendToChannel(context.Channel); return; } int mekosGained = (int)Math.Round((((Global.random.NextDouble() + 1.25) * 0.5) * 10) * thisGuild.CalculateLevel(thisGuild.Experience)); User user = await database.Users.FindAsync(context.Author.Id.ToDbLong()); await user.AddCurrencyAsync(context.Channel, null, mekosGained); await Utils.Embed .SetTitle(locale.GetString("miki_terms_weekly")) .AddInlineField("Mekos", mekosGained.ToString()) .SendToChannel(context.Channel); timer.Value = DateTime.Now; await database.SaveChangesAsync(); } else { await Utils.Embed .SetTitle(locale.GetString("miki_terms_weekly")) .SetDescription(context.GetResource("guildweekly_error_timer_running", (timer.Value.AddDays(7) - DateTime.Now).ToTimeString(locale))) .SendToChannel(context.Channel); } } else { await Utils.Embed .SetTitle(locale.GetString("miki_terms_weekly")) .SetDescription(locale.GetString("miki_guildweekly_insufficient_exp", thisGuild.MinimalExperienceToGetRewards)) .SendToChannel(context.Channel); } } }
internal CQCallbackTask(string queryId, string key, QueryChangeType changeType, string clientId, EventContext eventContext, EventDataFilter datafilter) { _queryId = queryId; _key = key; _changeType = changeType; _clientID = clientId; _eventContext = eventContext; _datafilter = datafilter; }