microsoft/teams.net
Publicmirrored fromhttps://github.com/microsoft/teams.netAvailable
Libraries/Microsoft.Teams.Apps/Events/Event.cs
63lines · modecode
| 1 | // Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | // Licensed under the MIT License. |
| 3 | |
| 4 | using System.Text.Json; |
| 5 | using System.Text.Json.Serialization; |
| 6 | |
| 7 | using Microsoft.Teams.Apps.Plugins; |
| 8 | |
| 9 | namespace Microsoft.Teams.Apps.Events; |
| 10 | |
| 11 | /// <summary> |
| 12 | /// the base Event payload type |
| 13 | /// </summary> |
| 14 | public class Event : Dictionary<string, object> |
| 15 | { |
| 16 | public object? GetOrDefault(string key) => ContainsKey(key) ? this[key] : null; |
| 17 | public T? GetOrDefault<T>(string key) => (T?)GetOrDefault(key); |
| 18 | |
| 19 | public object Get(string key) => this[key]; |
| 20 | public T Get<T>(string key) => (T)this[key]; |
| 21 | |
| 22 | public override string ToString() |
| 23 | { |
| 24 | return JsonSerializer.Serialize(this, new JsonSerializerOptions() |
| 25 | { |
| 26 | WriteIndented = true, |
| 27 | DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull |
| 28 | }); |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | [AttributeUsage(AttributeTargets.Method, Inherited = true)] |
| 33 | public class EventAttribute(string name) : Attribute |
| 34 | { |
| 35 | public readonly string Name = name; |
| 36 | } |
| 37 | |
| 38 | public static partial class AppEventExtensions |
| 39 | { |
| 40 | public static App OnEvent(this App app, string name, Action<IPlugin, Event> handler) |
| 41 | { |
| 42 | app.Events.On(name, handler); |
| 43 | return app; |
| 44 | } |
| 45 | |
| 46 | public static App OnEvent<TEvent>(this App app, string name, Action<IPlugin, TEvent> handler) where TEvent : Event |
| 47 | { |
| 48 | app.Events.On(name, (plugin, payload) => handler(plugin, (TEvent)payload)); |
| 49 | return app; |
| 50 | } |
| 51 | |
| 52 | public static App OnEvent(this App app, string name, Func<IPlugin, Event, CancellationToken, Task> handler) |
| 53 | { |
| 54 | app.Events.On(name, handler); |
| 55 | return app; |
| 56 | } |
| 57 | |
| 58 | public static App OnEvent<TEvent>(this App app, string name, Func<IPlugin, TEvent, CancellationToken, Task> handler) where TEvent : Event |
| 59 | { |
| 60 | app.Events.On(name, (plugin, payload, token) => handler(plugin, (TEvent)payload, token)); |
| 61 | return app; |
| 62 | } |
| 63 | } |