[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M69B7W12E3YMJAZNZBY9JK6M":3,"skill-same:01M69B7W12E3YMJAZNZBY9JK6M":65},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":8,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":18,"categories":19,"keywords":30,"publishedAt":36,"linkOnly":37,"markdownContent":38,"markdownBody":39,"frontMatter":40,"refName":41,"commitSha":42,"skillDirectory":43,"forksCount":44,"repositoryHtmlUrl":45,"repositoryHomepageUrl":46,"ownerHtmlUrl":47,"ownerBlogUrl":48,"ownerDescription":49,"updatedAt":50,"install":51,"resources":64},"01M69B7W12E3YMJAZNZBY9JK6M","agents-sdk-dotnet-activityhandler-migration","Agents SDK ActivityHandler 迁移","Use when migrating a Microsoft 365 Agents SDK agent that uses ActivityHandler or TeamsActivityHandler to AgentApplication. This is ONLY for DotNet projects that uses `Microsoft.Agents.*` packages.  Triggered by Agents SDK bots that subclass ActivityHandler or TeamsActivityHandler that need to be modernized to AgentApplication routing.","在将使用 ActivityHandler 或 TeamsActivityHandler 的 Microsoft 365 Agents SDK 智能体迁移到 AgentApplication 时使用。仅适用于使用 `Microsoft.Agents.*` 包的 DotNet 项目。当继承 ActivityHandler 或 TeamsActivityHandler 的 Agents SDK 机器人需要现代化改造为 AgentApplication 路由时触发。","microsoft\u002FAgents","microsoft","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F6154722?v=4","01M698VYDXZ6JW5WH3CRV650R8","Microsoft","01M69B7CR81D1HSNV69XDT8KAR",1109,"MIT",null,"https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002FAgents\u002Fblob\u002Fmain\u002Fagent-plugins\u002Fagents-for-net\u002Fskills\u002Fagents-sdk-dotnet-activityhandler-migration\u002FSKILL.md",[20,25],{"categoryNo":21,"categoryName":22,"taxonomyType":23,"taxonomyTypeDesc":24},"01M8BQ6TQZN6R52WBJ9H8NRMQM","软件开发工程师","PROFESSION","适用职业",{"categoryNo":26,"categoryName":27,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8C535N2MZ5XT7ANT9Z6FM48",".NET 依赖升级与迁移","SCENARIO","使用场景",[31,32,33,34,10,35],"agents sdk","sdk","dotnet","agents sdk dotnet activityhandler migration","packages","2026-11-10 10:12:30",false,"---\nname: agents-sdk-dotnet-activityhandler-migration\ndescription: Use when migrating a Microsoft 365 Agents SDK agent that uses ActivityHandler or TeamsActivityHandler to AgentApplication. This is ONLY for DotNet projects that uses `Microsoft.Agents.*` packages.  Triggered by Agents SDK bots that subclass ActivityHandler or TeamsActivityHandler that need to be modernized to AgentApplication routing.\n---\n\n# Agents SDK ActivityHandler → AgentApplication Migration (.NET)\n\n## Overview\n\nUpgrades a bot from the ActivityHandler compat layer to the modern `AgentApplication` routing pattern. This is ONLY for DotNet projects that already use `Microsoft.Agents.*` packages.  If the project is still using `Microsoft.Bot.*` packages the `bf-to-agents-sdk-dotnet-migration` skill should be used first.\n\n**Two entry points:**\n- **Standalone:** The bot already uses `Microsoft.Agents.*` packages, namespaces, and appsettings — focus is on the bot class, Program.cs, and endpoint mapping.\n- **Second step after `bf-to-agents-sdk-dotnet-migration`:** Packages, namespaces, and appsettings were converted in that step — this skill handles the AgentApplication conversion.\n\n---\n\n## What Does NOT Need to Change\n\nVerify each of these is already correct — do not modify unless broken:\n\n| Item | Expected State |\n|------|---------------|\n| Namespaces in bot class | Already `Microsoft.Agents.*` — only remove compat namespaces |\n| `appsettings.json` | Already has `Connections` + `TokenValidation` sections |\n| `builder.Services.AddAgentAspNetAuthentication(...)` | Already present — keep |\n| `AspNetExtensions.cs` (if present) | Sample-provided auth helper — keep as-is |\n| Custom DI in Program.cs | Preserve dialogs, adapters, custom services — **but remove `ConversationState` and `UserState`** (see Step 2) |\n\n> **⚠️ If beta packages are required:** Tell the user explicitly: *\"This migration uses pre-release (`-beta`) Agents SDK packages, which are nightly builds and not suitable for production. Upgrade to a stable release before deploying.\"*\n\n---\n\n## Handler Mapping: ActivityHandler → AgentApplication\n\n| ActivityHandler Override | AgentApplication Registration |\n|--------------------------|-------------------------------|\n| `OnMessageActivityAsync(ITurnContext\u003CIMessageActivity>, CT)` | `OnActivity(ActivityTypes.Message, handler, rank: RouteRank.Last)` |\n| `OnMembersAddedAsync(IList\u003CChannelAccount>, ITurnContext\u003CIConversationUpdateActivity>, CT)` | `OnConversationUpdate(ConversationUpdateEvents.MembersAdded, handler)` |\n| `OnMembersRemovedAsync(...)` | `OnConversationUpdate(ConversationUpdateEvents.MembersRemoved, handler)` |\n| `OnMessageUpdateActivityAsync(...)` | `OnActivity(ActivityTypes.MessageUpdate, handler)` |\n| `OnMessageDeleteActivityAsync(...)` | `OnActivity(ActivityTypes.MessageDelete, handler)` |\n| `OnReactionsAddedAsync(IList\u003CMessageReaction>, ...)` | `OnMessageReactionsAdded(handler)` |\n| `OnReactionsRemovedAsync(IList\u003CMessageReaction>, ...)` | `OnMessageReactionsRemoved(handler)` |\n| `OnEventAsync(ITurnContext\u003CIEventActivity>, CT)` | `OnEvent(eventName, handler)` or `OnActivity(ActivityTypes.Event, handler)` |\n| `OnInvokeActivityAsync(...)` with `adaptiveCard\u002Faction` + verb switch | `AdaptiveCards.OnActionExecute(verb, handler)` — one registration per verb (preferred) |\n| `OnInvokeActivityAsync(...)` with `application\u002Fsearch` | `AdaptiveCards.OnSearch(dataset, handler)` — one registration per `choices.data.dataset` value |\n| `OnInvokeActivityAsync(...)` (other invoke types) | `OnActivity(ActivityTypes.Invoke, handler)` |\n| `OnTurnAsync(...)` override (cross-cutting) | `OnBeforeTurn(handler)` \u002F `OnAfterTurn(handler)` |\n| `OnInstallationUpdateActivityAsync(...)` | `OnActivity(ActivityTypes.InstallationUpdate, handler)` |\n| `OnEndOfConversationActivityAsync(...)` | `OnActivity(ActivityTypes.EndOfConversation, handler)` |\n\n**Key difference:** Handler signature changes from `(ITurnContext\u003CT>, CT)` to `(ITurnContext, ITurnState, CT)`.\n`membersAdded`, `membersRemoved`, `messageReactions` are no longer separate parameters — access via `turnContext.Activity.*`.\n\n### `adaptiveCard\u002Faction` invokes → `AdaptiveCards.OnActionExecute`\n\nIf the bot overrides `OnInvokeActivityAsync` and switches on a verb from `adaptiveCard\u002Faction` activities, replace it with per-verb `AdaptiveCards.OnActionExecute` registrations. `AdaptiveCards` is a property on `AgentApplication` (no `RegisterExtension` needed):\n\n```csharp\n\u002F\u002F Before: one OnInvokeActivityAsync with switch(verb)\nprotected override async Task\u003CInvokeResponse> OnInvokeActivityAsync(ITurnContext\u003CIInvokeActivity> ctx, CancellationToken ct)\n{\n    if (ctx.Activity.Name == \"adaptiveCard\u002Faction\")\n    {\n        var wrapper = JsonSerializer.Deserialize\u003CAdaptiveCardInvokeValue>(ctx.Activity.Value.ToString());\n        switch (wrapper.Action.Verb)\n        {\n            case \"approve\": return CreateInvokeResponse(GetApproveCard(wrapper.Action.Data));\n            case \"reject\":  return CreateInvokeResponse(GetRejectCard(wrapper.Action.Data));\n        }\n    }\n    return null;\n}\n\n\u002F\u002F After: one registration per verb — framework filters and extracts action.data\npublic MyBot(AgentApplicationOptions options) : base(options)\n{\n    AdaptiveCards.OnActionExecute(\"approve\", OnApproveAsync);\n    AdaptiveCards.OnActionExecute(\"reject\",  OnRejectedAsync);\n}\n\n\u002F\u002F Handler receives action.data directly — NOT the full AdaptiveCardInvokeValue\n\u002F\u002F Return AdaptiveCardInvokeResponse directly — no CreateInvokeResponse() wrapper\nprivate Task\u003CAdaptiveCardInvokeResponse> OnApproveAsync(\n    ITurnContext turnContext, ITurnState turnState, object data, CancellationToken ct)\n{\n    var actionData = ProtocolJsonSerializer.ToObject\u003CMyDataModel>(data);  \u002F\u002F data == action.data\n    return Task.FromResult(new AdaptiveCardInvokeResponse\n    {\n        StatusCode = 200,\n        Type = \"application\u002Fvnd.microsoft.card.adaptive\",\n        Value = BuildCard(actionData)\n    });\n}\n```\n\n**Key points:**\n- `data` parameter = `invokeValue.Action.Data` — deserialize as your data model, not as `AdaptiveCardInvokeValue`\n- Return `AdaptiveCardInvokeResponse` directly — the framework wraps it in an `InvokeResponse` automatically\n- `CreateInvokeResponse()` is a compat-layer helper that does not exist on `AgentApplication`\n- Namespace: `using Microsoft.Agents.Builder.App.AdaptiveCards;`\n\n---\n\n## Step 1-a: Convert Bot Class to AgentApplication (not using Dialogs)\n\n- Remove `using Microsoft.Agents.Builder.Compat;` (ActivityHandler namespace)\n- Remove `using Microsoft.Agents.Extensions.Teams.Compat;` (TeamsActivityHandler namespace)\n- Keep all other `using Microsoft.Agents.*` statements — they are already correct\n\n```csharp\n\u002F\u002F Before: ActivityHandler compat layer\nusing Microsoft.Agents.Builder.Compat;         \u002F\u002F REMOVE\nusing Microsoft.Agents.Extensions.Teams.Compat; \u002F\u002F REMOVE if Teams\nusing Microsoft.Agents.Builder;\nusing Microsoft.Agents.Core.Models;\n\npublic class EchoBot : ActivityHandler  \u002F\u002F or TeamsActivityHandler\n{\n    protected override async Task OnMessageActivityAsync(ITurnContext\u003CIMessageActivity> turnContext, CancellationToken ct)\n    { \u002F* business logic *\u002F\n    }\n}\n\n\u002F\u002F After: AgentApplication\nusing Microsoft.Agents.Builder;\nusing Microsoft.Agents.Builder.App;\nusing Microsoft.Agents.Core.Models;\n\npublic class EchoBot : AgentApplication\n{\n    public EchoBot(AgentApplicationOptions options) : base(options)\n    {\n        OnConversationUpdate(ConversationUpdateEvents.MembersAdded, OnMembersAddedAsync);\n        OnActivity(ActivityTypes.Message, OnMessageAsync, rank: RouteRank.Last);\n    }\n\n    \u002F\u002F Signature: (ITurnContext, ITurnState, CancellationToken)\n    private async Task OnMessageAsync(ITurnContext ctx, ITurnState state, CancellationToken ct)\n    { \u002F* same business logic *\u002F }\n}\n```\n\nFor Teams bots (`TeamsActivityHandler`) with Teams-specific handlers (messaging extensions, task modules, etc.), see **Step 1-d** below.\n\n## Step 1-b: Convert Bot Class to AgentApplication (using Dialogs)\n\n- Remove `using Microsoft.Agents.Builder.Compat;` (ActivityHandler namespace)\n- Remove `using Microsoft.Agents.Extensions.Teams.Compat;` (TeamsActivityHandler namespace)\n- Keep all other `using Microsoft.Agents.*` statements — they are already correct\n\n```csharp\n\u002F\u002F Before: ActivityHandler compat layer\nusing Microsoft.Agents.Builder.Compat;         \u002F\u002F REMOVE\nusing Microsoft.Agents.Builder;\nusing Microsoft.Agents.Builder.State;\nusing Microsoft.Agents.Core.Models;\n\npublic class EchoBot : ActivityHandler\n{\n    protected override Task OnMessageActivityAsync(ITurnContext\u003CIMessageActivity> turnContext, CancellationToken ct)\n        => dialog.RunAsync(turnContext, conversationState, ct);\n}\n\n\u002F\u002F After: AgentApplication\nusing Microsoft.Agents.Builder;\nusing Microsoft.Agents.Builder.App;\nusing Microsoft.Agents.Builder.State;\nusing Microsoft.Agents.Core.Models;\n\npublic class EchoBot : AgentApplication\n{\n    public EchoBot(AgentApplicationOptions options, MainDialog dialog) : base(options)\n    {\n        _dialog = dialog;\n        OnActivity(ActivityTypes.Message, OnMessageAsync, rank: RouteRank.Last);\n        \u002F\u002F signin\u002FverifyState and signin\u002FtokenExchange are both matched by \"signin\u002F.*\"\n        OnActivity(\n            (ctx, ct) => Task.FromResult(ctx.Activity.IsType(ActivityTypes.Invoke) && ctx.Activity.Name != null && Regex.IsMatch(ctx.Activity.Name, \"signin\u002F.*\")),\n            OnSigninInvokeStateAsync);\n    }\n\n    \u002F\u002F Signature: (ITurnContext, ITurnState, CancellationToken) — NOT the ActivityHandler signature\n    private Task OnMessageAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken ct)\n        => _dialog.RunAsync(turnContext, turnState.Conversation, ct);\n\n    private Task OnSigninInvokeStateAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken ct)\n        => _dialog.RunAsync(turnContext, turnState.Conversation, ct);\n}\n```\n\n**Key differences from non-dialog migration:**\n- Do **not** inject `ConversationState` into the bot — pass `turnState.Conversation` to `Dialog.RunAsync` instead\n- Use `InvokeRouteBuilder` (not `OnActivity(ActivityTypes.Invoke, ...)`) to route signin invokes — the name pattern matches both `signin\u002FverifyState` and `signin\u002FtokenExchange`\n- Remove `ConversationState` and `UserState` from DI entirely — see Step 2\n\n> ⚠️ **Generic `DialogBot\u003CT>` base class pattern:** Some projects use a two-level class hierarchy where a generic base class (e.g. `DialogBot\u003CT> : ActivityHandler`) holds the dialog field, state injection, and `OnTurnAsync` state-saving override, and the concrete bot class (e.g. `MyBot : DialogBot\u003CMainDialog>`) only adds routing. Collapse both classes into a single non-generic `AgentApplication` subclass — inject the concrete dialog type directly in the constructor. The generic type parameter is not needed. Remove `OnTurnAsync` entirely (AgentApplication manages state automatically).\n\n---\n\n## Step 1-c: Remove State Management Boilerplate\n\n### Remove OnTurnBeginAsync \u002F OnTurnEndAsync Overrides\n\n`ActivityHandler` and `TeamsActivityHandler` bots sometimes manually load and save state in turn lifecycle overrides. Remove these entirely — `AgentApplication` handles state loading and saving automatically:\n\n```csharp\n\u002F\u002F REMOVE these overrides completely — AgentApplication does this automatically\nprotected override async Task OnTurnBeginAsync(ITurnContext turnContext, CancellationToken cancellationToken = default)\n{\n    await ConversationState.LoadAsync(turnContext, false, cancellationToken);\n    await UserState.LoadAsync(turnContext, false, cancellationToken);\n}\n\nprotected override async Task OnTurnEndAsync(ITurnContext turnContext, CancellationToken cancellationToken = default)\n{\n    await ConversationState.SaveChangesAsync(turnContext, false, cancellationToken);\n    await UserState.SaveChangesAsync(turnContext, false, cancellationToken);\n}\n```\n\nAlso remove any `ConversationState` or `UserState` properties\u002Ffields that were injected for this purpose.\n\n### Migrate CloudAdapter OnTurnError to AgentApplication\n\nIf a custom `CloudAdapter` subclass injects `ConversationState` only to call `DeleteStateAsync` on error, move that logic to an `AgentApplication.OnTurnError` handler instead.\n\n**Before — in the custom adapter:**\n```csharp\npublic MyAdapter(\n    IChannelServiceClientFactory channelServiceClientFactory,\n    IActivityTaskQueue activityTaskQueue,\n    ILogger\u003CCloudAdapter> logger,\n    ConversationState conversationState)   \u002F\u002F REMOVE this parameter\n    : base(channelServiceClientFactory, activityTaskQueue, logger: logger)\n{\n    OnTurnError = async (turnContext, exception) =>\n    {\n        if (conversationState != null)\n        {\n            await conversationState.DeleteStateAsync(turnContext);  \u002F\u002F REMOVE\n        }\n    };\n}\n```\n\n**After — remove ConversationState from the adapter:**\n```csharp\npublic MyAdapter(\n    IChannelServiceClientFactory channelServiceClientFactory,\n    IActivityTaskQueue activityTaskQueue,\n    ILogger\u003CCloudAdapter> logger)\n    : base(channelServiceClientFactory, activityTaskQueue, logger: logger)\n{\n    \u002F\u002F OnTurnError can remain for logging; state deletion moves to AgentApplication\n}\n```\n\n**Add to the AgentApplication bot constructor:**\n```csharp\npublic MyBot(AgentApplicationOptions options, ...) : base(options)\n{\n    OnTurnError(OnAgentTurnErrorAsync);\n    \u002F\u002F ... other route registrations\n}\n\nprivate async Task OnAgentTurnErrorAsync(ITurnContext turnContext, ITurnState turnState, Exception exception, CancellationToken cancellationToken)\n{\n    try\n    {\n        await turnState.Conversation.DeleteStateAsync(turnContext, cancellationToken);\n    }\n    catch(Exception ex)\n    {\n        Logger.LogError(ex, \"Exception deleting conversation state after a turn error.\");\n    }\n}\n```\n\nCustomer-written classes that accept `ConversationState` or `UserState` as constructor parameters can remain unchanged for now. However, they will ultimately need to source their state from `ITurnState.Conversation` or `ITurnState.User` — flag this to the customer as a follow-up item.\n\n### `application\u002Fsearch` invokes → `AdaptiveCards.OnSearch`\n\nIf the bot overrides `OnInvokeActivityAsync` and handles `activity.Name == \"application\u002Fsearch\"` (adaptive card typeahead\u002Fdynamic search), replace it with per-dataset `AdaptiveCards.OnSearch` registrations. The dataset name comes from `choices.data.dataset` in the card JSON. The handler returns `IList\u003CAdaptiveCardsSearchResult>` — the framework automatically wraps results in the `application\u002Fvnd.microsoft.search.searchResponse` format and sends the invoke response.\n\n```csharp\n\u002F\u002F Before: one OnInvokeActivityAsync checking activity.Name\nprotected override async Task\u003CInvokeResponse> OnInvokeActivityAsync(ITurnContext\u003CIInvokeActivity> turnContext, CancellationToken ct)\n{\n    if (turnContext.Activity.Name == \"application\u002Fsearch\")\n    {\n        var searchData = JsonSerializer.Deserialize\u003CDynamicSearchCard>(turnContext.Activity.Value.ToString());\n        \u002F\u002F ... build results ...\n        return new InvokeResponse { Status = 200, Body = searchResponseData };\n    }\n    return null;\n}\n\n\u002F\u002F After: per-dataset OnSearch registrations\npublic ActivityBot(AgentApplicationOptions options) : base(options)\n{\n    AdaptiveCards.OnSearch(\"npmpackages\", OnNpmSearchAsync);\n    AdaptiveCards.OnSearch(\"cities\", OnCitiesSearchAsync);\n}\n\n\u002F\u002F Handler signature: (ITurnContext, ITurnState, Query\u003CAdaptiveCardsSearchParams>, CT) → Task\u003CIList\u003CAdaptiveCardsSearchResult>>\nprivate async Task\u003CIList\u003CAdaptiveCardsSearchResult>> OnNpmSearchAsync(\n    ITurnContext turnContext, ITurnState turnState, Query\u003CAdaptiveCardsSearchParams> query, CancellationToken ct)\n{\n    \u002F\u002F query.Parameters.QueryText = search text typed by user\n    \u002F\u002F query.Parameters.Dataset  = \"npmpackages\"\n    \u002F\u002F ... fetch results ...\n    return results.Select(r => new AdaptiveCardsSearchResult(r.Title, r.Value)).ToList();\n}\n```\n\n**Key differences:**\n- Return `IList\u003CAdaptiveCardsSearchResult>` directly — no `InvokeResponse` wrapper\n- `AdaptiveCardsSearchResult(string title, string value)` — constructor takes title and value\n- `query.Parameters.QueryText` replaces `searchData.queryText`\n- `query.Parameters.Dataset` contains the dataset name (same as the registration key)\n\n> ⚠️ **Dependent dropdown — associated inputs not in `query`:** When a card uses `\"associatedInputs\": \"auto\"`, the selected values of other inputs are sent in the `data` field of the raw invoke payload — NOT in `query.Parameters`. Access them directly: `ProtocolJsonSerializer.ToObject\u003CMyModel>(turnContext.Activity.Value)` where `MyModel` maps the top-level `data` field.\n>\n> ```csharp\n> private Task\u003CIList\u003CAdaptiveCardsSearchResult>> OnCitiesSearchAsync(\n>     ITurnContext turnContext, ITurnState turnState, Query\u003CAdaptiveCardsSearchParams> query, CancellationToken ct)\n> {\n>     \u002F\u002F Associated input (country selector) arrives in activity.Value's \"data\" field\n>     var card = ProtocolJsonSerializer.ToObject\u003CDependantDropdownCard>(turnContext.Activity.Value);\n>     string country = card?.data?.choiceSelect?.ToLower() ?? \"\";\n>     \u002F\u002F ... return cities for country ...\n> }\n> ```\n\n---\n\n## Step 1-d: Convert TeamsActivityHandler with Teams-Specific Handlers\n\nFor bots that override Teams-specific methods (messaging extensions, task modules, etc.), use `RegisterExtension(new TeamsAgentExtension(this), ...)` inside the constructor.\n\n### TeamsActivityHandler → TeamsAgentExtension handler mapping\n\n**Message Extensions** — handlers return `Task\u003CMessagingExtensionResult>` (not `MessagingExtensionResponse`):\n\n| TeamsActivityHandler Override | TeamsAgentExtension Registration | Handler Delegate |\n|-------------------------------|----------------------------------|-----------------|\n| `OnTeamsMessagingExtensionQueryAsync(ctx, MessagingExtensionQuery, CT)` | `teams.MessageExtensions.OnQuery(commandId, handler)` | `(ITurnContext, ITurnState, Query\u003CIDictionary\u003Cstring,object>>, CT) → Task\u003CMessagingExtensionResult>` |\n| `OnTeamsMessagingExtensionSelectItemAsync(ctx, JsonElement, CT)` | `teams.MessageExtensions.OnSelectItem(handler)` | `(ITurnContext, ITurnState, object item, CT) → Task\u003CMessagingExtensionResult>` |\n| `OnTeamsAppBasedLinkQueryAsync(ctx, AppBasedLinkQuery, CT)` | `teams.MessageExtensions.OnQueryLink(handler)` | `(ITurnContext, ITurnState, string url, CT) → Task\u003CMessagingExtensionResult>` |\n| `OnTeamsAnonymousAppBasedLinkQueryAsync(ctx, AppBasedLinkQuery, CT)` | `teams.MessageExtensions.OnAnonymousQueryLink(handler)` | `(ITurnContext, ITurnState, string url, CT) → Task\u003CMessagingExtensionResult>` |\n| `OnTeamsMessagingExtensionFetchTaskAsync(ctx, MessagingExtensionAction, CT)` | `teams.MessageExtensions.OnFetchTask(commandId, handler)` | `(ITurnContext, ITurnState, CT) → Task\u003CTaskModuleResponse>` |\n| `OnTeamsMessagingExtensionSubmitActionAsync(ctx, MessagingExtensionAction, CT)` | `teams.MessageExtensions.OnSubmitAction(commandId, handler)` | `(ITurnContext, ITurnState, object data, CT) → Task\u003CMessagingExtensionActionResponse>` |\n| `OnTeamsMessagingExtensionAgentMessagePreviewEditAsync(ctx, MessagingExtensionAction, CT)` | `teams.MessageExtensions.OnAgentMessagePreviewEdit(commandId, handler)` | `(ITurnContext, ITurnState, IActivity activityPreview, CT) → Task\u003CMessagingExtensionActionResponse>` |\n| `OnTeamsMessagingExtensionAgentMessagePreviewSendAsync(ctx, MessagingExtensionAction, CT)` | `teams.MessageExtensions.OnAgentMessagePreviewSend(commandId, handler)` | `(ITurnContext, ITurnState, IActivity activityPreview, CT) → Task` |\n| `OnTeamsMessagingExtensionConfigurationQuerySettingUrlAsync(ctx, MessagingExtensionQuery, CT)` | `teams.MessageExtensions.OnQueryUrlSetting(handler)` | `(ITurnContext, ITurnState, CT) → Task\u003CMessagingExtensionResult>` |\n| `OnTeamsMessagingExtensionConfigurationSettingAsync(ctx, JsonElement, CT)` | `teams.MessageExtensions.OnConfigureSettings(handler)` | `(ITurnContext, ITurnState, object settings, CT) → Task` |\n| `OnTeamsMessagingExtensionCardButtonClickedAsync(ctx, JsonElement, CT)` | `teams.MessageExtensions.OnCardButtonClicked(handler)` | `(ITurnContext, ITurnState, object cardData, CT) → Task` |\n\n**Task Modules:**\n\n| TeamsActivityHandler Override | TeamsAgentExtension Registration | Handler Delegate |\n|-------------------------------|----------------------------------|-----------------|\n| `OnTeamsTaskModuleFetchAsync(ctx, TaskModuleRequest, CT)` | `teams.TaskModules.OnFetch(verb, handler)` | `(ITurnContext, ITurnState, object data, CT) → Task\u003CTaskModuleResponse>` |\n| `OnTeamsTaskModuleSubmitAsync(ctx, TaskModuleRequest, CT)` | `teams.TaskModules.OnSubmit(verb, handler)` | `(ITurnContext, ITurnState, object data, CT) → Task\u003CTaskModuleResponse>` |\n\n**⚠️ Task Module verb matching:** `OnFetch` and `OnSubmit` match by looking for a `verb` field inside `activity.Value.data`. If the submitted data has **no `verb` field**, use the `RouteSelector` overload instead:\n\n```csharp\nteams.TaskModules.OnSubmit(\n    (ctx, ct) => Task.FromResult(\n        string.Equals(ctx.Activity.Type, ActivityTypes.Invoke, StringComparison.OrdinalIgnoreCase) &&\n        string.Equals(ctx.Activity.Name, \"task\u002Fsubmit\", StringComparison.OrdinalIgnoreCase)),\n    OnTaskModuleSubmitAsync);\n```\n\n**⚠️ `data` parameter in submit handler:** The `data` parameter passed to `SubmitHandlerAsync` is `taskModuleAction.Value` from a `CardAction` deserialization of the payload. For `task\u002Fsubmit` payloads where the top-level JSON has no `\"value\"` key (only `\"data\"` and `\"context\"`), this will be `null`. Access the submitted data via `turnContext.Activity.Value` directly:\n\n```csharp\nprivate async Task\u003CTaskModuleResponse> OnTaskModuleSubmitAsync(\n    ITurnContext turnContext, ITurnState turnState, object data, CancellationToken cancellationToken)\n{\n    \u002F\u002F data parameter is null when payload has no top-level \"value\" key — use Activity.Value instead\n    var request = ProtocolJsonSerializer.ToObject\u003CTaskModuleRequest>(turnContext.Activity.Value);\n    var feedback = ProtocolJsonSerializer.ToObject\u003CMySubmitModel>(request.Data);\n    \u002F\u002F ...\n    return null; \u002F\u002F null dismisses the task module\n}\n```\n\n**Meetings:**\n\n| TeamsActivityHandler Override | TeamsAgentExtension Registration | Handler Delegate |\n|-------------------------------|----------------------------------|-----------------|\n| `OnTeamsMeetingStartAsync(MeetingStartEventDetails, ctx, CT)` | `teams.Meetings.OnStart(handler)` | `(ITurnContext, ITurnState, MeetingStartEventDetails, CT) → Task` |\n| `OnTeamsMeetingEndAsync(MeetingEndEventDetails, ctx, CT)` | `teams.Meetings.OnEnd(handler)` | `(ITurnContext, ITurnState, MeetingEndEventDetails, CT) → Task` |\n| `OnTeamsMeetingParticipantsJoinAsync(MeetingParticipantsEventDetails, ctx, CT)` | `teams.Meetings.OnParticipantsJoin(handler)` | `(ITurnContext, ITurnState, MeetingParticipantsEventDetails, CT) → Task` |\n| `OnTeamsMeetingParticipantsLeaveAsync(MeetingParticipantsEventDetails, ctx, CT)` | `teams.Meetings.OnParticipantsLeave(handler)` | `(ITurnContext, ITurnState, MeetingParticipantsEventDetails, CT) → Task` |\n\n**Messages (edit\u002Fdelete):**\n\n| TeamsActivityHandler Override | TeamsAgentExtension Registration |\n|-------------------------------|----------------------------------|\n| `OnTeamsMessageEditAsync(ctx, CT)` | `teams.OnMessageEdit(handler)` |\n| `OnTeamsMessageUndeleteAsync(ctx, CT)` | `teams.OnMessageUndelete(handler)` |\n| `OnTeamsMessageSoftDeleteAsync(ctx, CT)` | `teams.OnMessageDelete(handler)` |\n| `OnTeamsReadReceiptAsync(ReadReceiptInfo, ctx, CT)` | `teams.OnTeamsReadReceipt(handler)` |\n\n**File Consent:**\n\n| TeamsActivityHandler Override | TeamsAgentExtension Registration |\n|-------------------------------|----------------------------------|\n| `OnTeamsFileConsentAcceptAsync(ctx, FileConsentCardResponse, CT)` | `teams.OnFileConsentAccept(handler)` |\n| `OnTeamsFileConsentDeclineAsync(ctx, FileConsentCardResponse, CT)` | `teams.OnFileConsentDecline(handler)` |\n\n**Bot Config:**\n\n| TeamsActivityHandler Override | TeamsAgentExtension Registration |\n|-------------------------------|----------------------------------|\n| `OnTeamsConfigFetchAsync(ctx, JsonElement, CT)` | `teams.OnConfigFetch(handler)` |\n| `OnTeamsConfigSubmitAsync(ctx, JsonElement, CT)` | `teams.OnConfigSubmit(handler)` |\n\n**Channels, Teams, Members** — all route through `teams.OnConversationUpdate(eventName, handler)` with constants from `TeamsConversationUpdateEvents`:\n\n| TeamsActivityHandler Override | Event Constant |\n|-------------------------------|----------------|\n| `OnTeamsMembersAddedAsync` | `ConversationUpdateEvents.MembersAdded` |\n| `OnTeamsMembersRemovedAsync` | `ConversationUpdateEvents.MembersRemoved` |\n| `OnTeamsChannelCreatedAsync` | `TeamsConversationUpdateEvents.ChannelCreated` |\n| `OnTeamsChannelDeletedAsync` | `TeamsConversationUpdateEvents.ChannelDeleted` |\n| `OnTeamsChannelRenamedAsync` | `TeamsConversationUpdateEvents.ChannelRenamed` |\n| `OnTeamsChannelRestoredAsync` | `TeamsConversationUpdateEvents.ChannelRestored` |\n| `OnTeamsTeamArchivedAsync` | `TeamsConversationUpdateEvents.TeamArchived` |\n| `OnTeamsTeamUnarchivedAsync` | `TeamsConversationUpdateEvents.TeamUnarchived` |\n| `OnTeamsTeamDeletedAsync` | `TeamsConversationUpdateEvents.TeamDeleted` |\n| `OnTeamsTeamHardDeletedAsync` | `TeamsConversationUpdateEvents.TeamHardDeleted` |\n| `OnTeamsTeamRenamedAsync` | `TeamsConversationUpdateEvents.TeamRenamed` |\n| `OnTeamsTeamRestoredAsync` | `TeamsConversationUpdateEvents.TeamRestored` |\n\n**Other:**\n\n| TeamsActivityHandler Override | TeamsAgentExtension Registration |\n|-------------------------------|----------------------------------|\n| `OnTeamsO365ConnectorCardActionAsync(ctx, O365ConnectorCardActionQuery, CT)` | `teams.OnO365ConnectorCardAction(handler)` |\n| `OnTeamsSigninVerifyStateAsync(ctx, CT)` | On `AgentApplication` directly: `OnActivity((ctx, ct) => Task.FromResult(ctx.Activity.IsType(ActivityTypes.Invoke) && Regex.IsMatch(ctx.Activity.Name, \"signin\u002F.*\")), handler)` |\n| `OnTeamsTabFetchAsync(ctx, TabRequest, CT)` | No direct equivalent — use `OnActivity(ActivityTypes.Invoke, handler)` with a name filter |\n| `OnTeamsTabSubmitAsync(ctx, TabSubmit, CT)` | No direct equivalent — use `OnActivity(ActivityTypes.Invoke, handler)` with a name filter |\n\n### Handler signature changes\n\n**Query handler** — return type changes from `Task\u003CMessagingExtensionResponse>` to `Task\u003CMessagingExtensionResult>`:\n```csharp\n\u002F\u002F Before\nprotected override async Task\u003CMessagingExtensionResponse> OnTeamsMessagingExtensionQueryAsync(\n    ITurnContext\u003CIInvokeActivity> turnContext, MessagingExtensionQuery query, CancellationToken ct)\n{\n    var text = query?.Parameters?[0]?.Value?.ToString();  \u002F\u002F index-based parameter access\n    \u002F\u002F ...\n    return new MessagingExtensionResponse { ComposeExtension = new MessagingExtensionResult { ... } };\n}\n\n\u002F\u002F After — registered as: teams.MessageExtensions.OnQuery(\"commandId\", OnQueryAsync)\nprivate async Task\u003CMessagingExtensionResult> OnQueryAsync(\n    ITurnContext turnContext, ITurnState turnState,\n    Query\u003CIDictionary\u003Cstring, object>> query, CancellationToken ct)\n{\n    \u002F\u002F Named parameter access — value is a JsonElement\n    string text = string.Empty;\n    if (query.Parameters.TryGetValue(\"paramName\", out var val) && val is JsonElement el)\n        text = el.GetString() ?? string.Empty;\n    \u002F\u002F ...\n    return new MessagingExtensionResult { Type = \"result\", AttachmentLayout = \"list\", Attachments = attachments };\n    \u002F\u002F NOTE: return MessagingExtensionResult directly — no MessagingExtensionResponse wrapper\n}\n```\n\n**SelectItem handler** — `item` is now `object` (cast to `JsonElement`):\n```csharp\n\u002F\u002F Before\nprotected override Task\u003CMessagingExtensionResponse> OnTeamsMessagingExtensionSelectItemAsync(\n    ITurnContext\u003CIInvokeActivity> turnContext, JsonElement query, CancellationToken ct)\n{\n    string id = query.GetProperty(\"packageId\").GetString();\n    return Task.FromResult(new MessagingExtensionResponse { ComposeExtension = new MessagingExtensionResult { ... } });\n}\n\n\u002F\u002F After — registered as: teams.MessageExtensions.OnSelectItem(OnSelectItemAsync)\nprivate Task\u003CMessagingExtensionResult> OnSelectItemAsync(\n    ITurnContext turnContext, ITurnState turnState, object item, CancellationToken ct)\n{\n    JsonElement query = (JsonElement)item;\n    string id = query.GetProperty(\"packageId\").GetString();\n    return Task.FromResult(new MessagingExtensionResult { Type = \"result\", ... });\n    \u002F\u002F NOTE: return MessagingExtensionResult directly — no MessagingExtensionResponse wrapper\n}\n```\n\n### Full registration pattern\n\n```csharp\nusing Microsoft.Agents.Builder.App;             \u002F\u002F AgentApplication\nusing Microsoft.Agents.Builder.App.AdaptiveCards; \u002F\u002F Query\u003CT>\nusing Microsoft.Agents.Builder.State;            \u002F\u002F ITurnState\nusing Microsoft.Agents.Extensions.Teams.App;    \u002F\u002F TeamsAgentExtension\nusing Microsoft.Agents.Extensions.Teams.Models; \u002F\u002F MessagingExtensionResult, etc.\n\u002F\u002F REMOVE: using Microsoft.Agents.Extensions.Teams.Compat;\n\npublic class MyTeamsBot : AgentApplication\n{\n    public MyTeamsBot(AgentApplicationOptions options) : base(options)\n    {\n        RegisterExtension(new TeamsAgentExtension(this), teams =>\n        {\n            teams.MessageExtensions.OnQuery(\"searchCommandId\", OnQueryAsync);\n            teams.MessageExtensions.OnSelectItem(OnSelectItemAsync);\n        });\n    }\n}\n```\n\n**Key differences:**\n- Helper methods that returned `MessagingExtensionResponse` must be changed to return `MessagingExtensionResult` — drop the outer `new MessagingExtensionResponse { ComposeExtension = ... }` wrapper\n- `MessagingExtensionQuery.Parameters[index].Value` → `Query\u003CIDictionary\u003Cstring,object>>.Parameters.TryGetValue(\"name\", out var val)` where `val` is a `JsonElement`\n- `commandId` in `OnQuery(commandId, ...)` must match the command `id` in the Teams app manifest\n\n---\n\n## Step 2: Update Program.cs\n\n### Add `AddAgentApplicationOptions`\n\nAdd this call **before** `builder.AddAgent\u003CT>()` — it is required for `AgentApplication` and was absent in ActivityHandler-based bots:\n\n```csharp\nbuilder.AddAgentApplicationOptions();  \u002F\u002F ADD THIS — required for AgentApplication\nbuilder.AddAgent\u003CEchoBot>();           \u002F\u002F existing line — keep\n```\n\n### Ensure IStorage Is Registered\n\n`AgentApplication` always requires an `IStorage` registration — even if the bot has no dialogs or explicit state usage. If it is not already present, add it:\n\n```csharp\nbuilder.Services.AddSingleton\u003CIStorage, MemoryStorage>(); \u002F\u002F always required by AgentApplication\n```\n\n### Remove ConversationState and UserState from DI\n\n`AgentApplication` manages state internally via `ITurnState`. Remove these registrations entirely:\n\n```csharp\n\u002F\u002F REMOVE both of these — AgentApplication does not use them\n\u002F\u002F builder.Services.AddSingleton\u003CConversationState>();\n\u002F\u002F builder.Services.AddSingleton\u003CUserState>();\n\nbuilder.Services.AddSingleton\u003CIStorage, MemoryStorage>(); \u002F\u002F keep — required by AgentApplication\nbuilder.Services.AddSingleton\u003CMainDialog>();               \u002F\u002F keep — dialog class itself is still needed\nbuilder.Services.AddSingleton\u003CIMyService, MyService>();    \u002F\u002F keep all custom services\n```\n\n### Preserve All Other Custom DI\n\nKeep dialogs, storage, adapters, and custom services. Only `ConversationState` and `UserState` are removed.\n\n### TeamsSSOTokenExchangeMiddleware\n\nIf the ActivityHandler bot registered `TeamsSSOTokenExchangeMiddleware`, **remove it** — it is not required and should not be used with `AgentApplication`. Remove it from DI and from any `IMiddleware[]` array registration.\n\n---\n\n## Step 3: Update Endpoint Mapping\n\nIdentify which endpoint pattern the existing bot uses, then apply the corresponding change.\n\n### Pattern A: `app.MapControllers()` + `BotController.cs` (most common in Agents SDK compat samples)\n\n```csharp\n\u002F\u002F Before Program.cs\nbuilder.Services.AddControllers();           \u002F\u002F needed for MapControllers\n\u002F\u002F ...\napp.MapControllers().AllowAnonymous();       \u002F\u002F dev\napp.MapControllers();                        \u002F\u002F prod\n\n\u002F\u002F After Program.cs\n\u002F\u002F Remove AddControllers() ONLY IF no other MVC controllers exist in the project\n\u002F\u002F Add authentication middleware if not already present:\napp.UseAuthentication();\napp.UseAuthorization();\napp.MapAgentRootEndpoint();                                              \u002F\u002F optional GET \"\u002F\"\napp.MapAgentApplicationEndpoints(requireAuth: !app.Environment.IsDevelopment());\n```\n\nDelete `BotController.cs`. Check first that it contains no custom logic beyond calling `adapter.ProcessAsync` — if it does, preserve that logic.\n\n**If the project uses Razor Pages** (`AddRazorPages()` \u002F `MapRazorPages()`): keep both — they serve web UI pages unrelated to the bot endpoint. Remove `AddControllers()`, `AddMvc()`, and any `MapControllerRoute()` \u002F `MapControllers()` calls, but leave the Razor Pages registrations in place:\n\n```csharp\n\u002F\u002F Keep — serves Razor Pages for web UI\nbuilder.Services.AddRazorPages();\n\u002F\u002F ...\napp.UseAuthentication();\napp.UseAuthorization();\napp.MapRazorPages();                   \u002F\u002F keep\napp.MapAgentRootEndpoint();\napp.MapAgentApplicationEndpoints(requireAuth: !app.Environment.IsDevelopment());\n```\n\nAlso remove the dev branch `app.MapControllers().AllowAnonymous()` pattern — auth is now handled by `requireAuth` on `MapAgentApplicationEndpoints`.\n\n### Pattern B: `app.MapAgentEndpoints()`\n\n```csharp\n\u002F\u002F Before\napp.MapAgentEndpoints(requireAuth: !app.Environment.IsDevelopment());\n\n\u002F\u002F After\napp.MapAgentRootEndpoint();\napp.MapAgentApplicationEndpoints(requireAuth: !app.Environment.IsDevelopment());\n```\n\n### Pattern C: `app.MapPost(...)` (older minimal API)\n\nOffer to switch. If accepted:\n\n```csharp\n\u002F\u002F Remove:\napp.MapPost(\"\u002Fapi\u002Fmessages\", async (HttpRequest req, HttpResponse res, IAgentHttpAdapter adapter, IAgent bot, CancellationToken ct)\n    => await adapter.ProcessAsync(req, res, bot, ct)).AllowAnonymous();\n\n\u002F\u002F Add:\napp.UseAuthentication();\napp.UseAuthorization();\napp.MapAgentRootEndpoint();\napp.MapAgentApplicationEndpoints(requireAuth: !app.Environment.IsDevelopment());\n```\n\n### Step 4 or at the very end of the migration:  Ask user if they would like to write the learnings from this migration to a markdown file they could submit to use to help us improve the skill.\n\n---\n\n## Development URL\n\nIf the existing bot had `app.Urls.Add(\"http:\u002F\u002Flocalhost:3978\")` inside an `IsDevelopment()` check, keep it. If it was missing, add it:\n\n```csharp\nif (app.Environment.IsDevelopment())\n{\n    app.Urls.Add(\"http:\u002F\u002Flocalhost:3978\");\n}\n```\n\n---\n\n## Middleware Replacements\n\nSome Bot Framework middleware has a direct equivalent in AgentApplication configuration.\n\n### ShowTypingMiddleware → StartTypingTimer\n\nDrop the `ShowTypingMiddleware` registration and enable the built-in typing timer instead:\n\n```csharp\n\u002F\u002F Remove from adapter setup:\n\u002F\u002F adapter.Use(new ShowTypingMiddleware());\n```\n\n```json\n\u002F\u002F appsettings.json — add to AgentApplication section:\n\"AgentApplication\": {\n  \"StartTypingTimer\": true\n}\n```\n\n### AutoSaveStateMiddleware\n\n`AgentApplication` loads and saves state automatically on every turn. **Always remove `AutoSaveStateMiddleware`** — it is no longer needed and must not be used with `AgentApplication`.\n\n```csharp\n\u002F\u002F REMOVE — always:\n\u002F\u002F new AutoSaveStateMiddleware(...)\n\u002F\u002F adapter.Use(new AutoSaveStateMiddleware(...));\n```\n\nIf removing it empties the `IMiddleware[]` DI registration, remove that registration entirely as well.\n\n### NormalizeMentionsMiddleware → NormalizeMentions \u002F RemoveRecipientMention\n\nDrop the `NormalizeMentionsMiddleware` registration and enable the equivalent settings instead:\n\n```csharp\n\u002F\u002F Remove from adapter setup:\n\u002F\u002F adapter.Use(new NormalizeMentionsMiddleware());\n```\n\n```json\n\u002F\u002F appsettings.json — add to AgentApplication section:\n\"AgentApplication\": {\n  \"NormalizeMentions\": true,\n  \"RemoveRecipientMention\": true\n}\n```\n\n---\n\n## Files to Delete\n\n| File | When to delete |\n|------|----------------|\n| `BotController.cs` | Always when switching to `MapAgentApplicationEndpoints` — unless it has custom logic beyond `ProcessAsync` |\n| `Controllers\u002F` folder | After deleting `BotController.cs`, if no other controllers remain |\n\nDo **not** delete `AspNetExtensions.cs` — if present it is providing the `AddAgentAspNetAuthentication` extension and must be kept.\n\n---\n\n## Common Mistakes\n\n| Mistake | Fix |\n|---------|-----|\n| Forgot `builder.AddAgentApplicationOptions()` | Add before `builder.AddAgent\u003CT>()` |\n| Removed custom DI (dialogs, state, services) | Restore — never remove developer-added registrations |\n| Added `[Agent]` attribute to AgentApplication class | Not required — `MapAgentApplicationEndpoints` discovers `AgentApplication` subclasses without it |\n| Left `using Microsoft.Agents.Builder.Compat` | Remove — ActivityHandler is gone |\n| Left `using Microsoft.Agents.Extensions.Teams.Compat` on main class | Remove — TeamsActivityHandler is gone; use `RegisterExtension(new TeamsAgentExtension(this), ...)` instead |\n| Teams MessageExtension handler returns `MessagingExtensionResponse` | Change return type to `MessagingExtensionResult` — the framework no longer uses the `ComposeExtension` wrapper; return the inner result directly |\n| Teams query parameter accessed by index (`query.Parameters[0].Value`) | Use named access: `query.Parameters.TryGetValue(\"paramName\", out var val)` where `val` is a `JsonElement`; parameter name comes from the Teams app manifest command definition |\n| Teams SelectItem handler uses `JsonElement` parameter | In `OnSelectItem`, the parameter type is `object`; cast it: `JsonElement query = (JsonElement)item` |\n| Missing `Microsoft.Agents.Extensions.Teams.App` namespace for TeamsAgentExtension | Add `using Microsoft.Agents.Extensions.Teams.App;` — `TeamsAgentExtension` is not in the Compat namespace |\n| Missing `Microsoft.Agents.Builder.App.AdaptiveCards` namespace for `Query\u003CT>` | Add `using Microsoft.Agents.Builder.App.AdaptiveCards;` — required for `Query\u003CIDictionary\u003Cstring, object>>` handler parameter |\n| `AdaptiveCard` is ambiguous after adding `using Microsoft.Agents.Builder.App.AdaptiveCards` | Conflict with `AdaptiveCards.AdaptiveCard` from the AdaptiveCards NuGet package. Use an alias instead: `using AgentAdaptiveCards = Microsoft.Agents.Builder.App.AdaptiveCards;` then reference `AgentAdaptiveCards.Query\u003CIDictionary\u003Cstring, object>>` in the handler signature |\n| Kept `builder.Services.AddControllers()` but deleted all controllers | Remove — no longer needed without MVC controllers |\n| Missing `app.UseAuthentication()` \u002F `app.UseAuthorization()` after switching from MapControllers | Add them before `MapAgentApplicationEndpoints` |\n| Injected `ConversationState` into bot constructor for dialogs | Remove from bot — use `turnState.Conversation` in `Dialog.RunAsync` calls instead |\n| Left `ConversationState` registered in DI | Remove — AgentApplication manages state internally via `ITurnState` |\n| Left `UserState` registered in DI | Remove — AgentApplication does not use it |\n| Left `AutoSaveStateMiddleware` registered | Remove entirely — AgentApplication saves state automatically; never keep it |\n| Left `ConversationState` injected in custom adapter `OnTurnError` for `DeleteStateAsync` | Remove the parameter; move `DeleteStateAsync` into an `AgentApplication.OnTurnError` handler using `turnState.Conversation.DeleteStateAsync` |\n| Left `OnTurnBeginAsync`\u002F`OnTurnEndAsync` overrides that load\u002Fsave state | Remove entirely — AgentApplication handles this automatically |\n| Kept generic `DialogBot\u003CT>` base class as a separate file | Collapse both classes into a single non-generic `AgentApplication` subclass; inject the concrete dialog type directly; delete the generic base class file |\n| Left `TeamsSSOTokenExchangeMiddleware` in DI or `IMiddleware[]` | Remove — not required and should not be used with AgentApplication |\n| Manually calling `SaveChangesAsync` in AgentApplication handlers | Remove — state is saved automatically |\n| Left `ShowTypingMiddleware` registration | Drop it; set `\"AgentApplication\": { \"StartTypingTimer\": true }` in appsettings.json |\n| Left `NormalizeMentionsMiddleware` registration | Drop it; set `NormalizeMentions` and\u002For `RemoveRecipientMention` to `true` in `AgentApplication` appsettings |\n| Handler accesses `membersAdded` as a parameter | Use `turnContext.Activity.MembersAdded` instead — it is no longer passed as a parameter |\n| Used `ProjectReference` to local SDK source instead of NuGet packages | Always use NuGet packages — customers don't have access to the SDK source repo |\n| Custom adapter constructor uses `ILogger\u003CIAgentHttpAdapter>` | Change to `ILogger\u003CCloudAdapter>` — `CloudAdapter` base constructor requires the concrete type, not the interface |\n| Changed business logic during migration | Do not — only change structure\u002Fregistration\u002Frouting |\n| Missing `IStorage` registration | Add `builder.Services.AddSingleton\u003CIStorage, MemoryStorage>();` — always required by AgentApplication, not just for dialog bots |\n| Used `OnActivity(ActivityTypes.Invoke, ...)` for `adaptiveCard\u002Faction` verbs | Use `AdaptiveCards.OnActionExecute(verb, handler)` instead — it's built into `AgentApplication`, matches by verb, and handles the invoke response automatically |\n| Called `CreateInvokeResponse(...)` in an `OnActionExecute` handler | `CreateInvokeResponse` is a compat-layer helper — it doesn't exist on `AgentApplication`. Return `AdaptiveCardInvokeResponse` directly; the framework wraps it |\n| Deserialized `data` as `AdaptiveCardInvokeValue` in `OnActionExecute` handler | The `data` parameter is already `invokeValue.Action.Data` — deserialize directly as your data model, not as the full invoke value wrapper |\n| `teams.TaskModules.OnSubmit(verb, ...)` never triggers | Default filter matches `activity.Value.data.verb` — if the submitted data has no `verb` field, use the `RouteSelector` overload with a custom selector that checks `ctx.Activity.Name == \"task\u002Fsubmit\"` |\n| `data` parameter is null in `SubmitHandlerAsync` | The `data` parameter is `taskModuleAction.Value` (CardAction), which is null when the payload has no top-level `\"value\"` key. Parse the submitted data directly: `ProtocolJsonSerializer.ToObject\u003CTaskModuleRequest>(turnContext.Activity.Value).Data` |\n| Removed `AddRazorPages()` \u002F `MapRazorPages()` when deleting BotController | Keep them — they serve web UI pages unrelated to the bot; only remove `AddControllers()`, `AddMvc()`, and `MapControllers()`\u002F`MapControllerRoute()` |\n| Used `OnActivity(ActivityTypes.Invoke, ...)` for `application\u002Fsearch` | Use `AdaptiveCards.OnSearch(dataset, handler)` instead — routes by `choices.data.dataset` value, handles invoke response automatically, handler returns `IList\u003CAdaptiveCardsSearchResult>` |\n| `OnSearch` handler returns `InvokeResponse` | Return `IList\u003CAdaptiveCardsSearchResult>` — the framework wraps results in `application\u002Fvnd.microsoft.search.searchResponse` and sends the invoke response |\n| Looked for associated input values (dependent dropdown) in `query.Parameters` | Associated inputs from `\"associatedInputs\": \"auto\"` arrive in the `data` field of the raw invoke payload, not in `query.Parameters`. Read them via `ProtocolJsonSerializer.ToObject\u003CMyModel>(turnContext.Activity.Value)` |\n","# Agents SDK ActivityHandler → AgentApplication Migration (.NET)\n\n## Overview\n\nUpgrades a bot from the ActivityHandler compat layer to the modern `AgentApplication` routing pattern. This is ONLY for DotNet projects that already use `Microsoft.Agents.*` packages.  If the project is still using `Microsoft.Bot.*` packages the `bf-to-agents-sdk-dotnet-migration` skill should be used first.\n\n**Two entry points:**\n- **Standalone:** The bot already uses `Microsoft.Agents.*` packages, namespaces, and appsettings — focus is on the bot class, Program.cs, and endpoint mapping.\n- **Second step after `bf-to-agents-sdk-dotnet-migration`:** Packages, namespaces, and appsettings were converted in that step — this skill handles the AgentApplication conversion.\n\n---\n\n## What Does NOT Need to Change\n\nVerify each of these is already correct — do not modify unless broken:\n\n| Item | Expected State |\n|------|---------------|\n| Namespaces in bot class | Already `Microsoft.Agents.*` — only remove compat namespaces |\n| `appsettings.json` | Already has `Connections` + `TokenValidation` sections |\n| `builder.Services.AddAgentAspNetAuthentication(...)` | Already present — keep |\n| `AspNetExtensions.cs` (if present) | Sample-provided auth helper — keep as-is |\n| Custom DI in Program.cs | Preserve dialogs, adapters, custom services — **but remove `ConversationState` and `UserState`** (see Step 2) |\n\n> **⚠️ If beta packages are required:** Tell the user explicitly: *\"This migration uses pre-release (`-beta`) Agents SDK packages, which are nightly builds and not suitable for production. Upgrade to a stable release before deploying.\"*\n\n---\n\n## Handler Mapping: ActivityHandler → AgentApplication\n\n| ActivityHandler Override | AgentApplication Registration |\n|--------------------------|-------------------------------|\n| `OnMessageActivityAsync(ITurnContext\u003CIMessageActivity>, CT)` | `OnActivity(ActivityTypes.Message, handler, rank: RouteRank.Last)` |\n| `OnMembersAddedAsync(IList\u003CChannelAccount>, ITurnContext\u003CIConversationUpdateActivity>, CT)` | `OnConversationUpdate(ConversationUpdateEvents.MembersAdded, handler)` |\n| `OnMembersRemovedAsync(...)` | `OnConversationUpdate(ConversationUpdateEvents.MembersRemoved, handler)` |\n| `OnMessageUpdateActivityAsync(...)` | `OnActivity(ActivityTypes.MessageUpdate, handler)` |\n| `OnMessageDeleteActivityAsync(...)` | `OnActivity(ActivityTypes.MessageDelete, handler)` |\n| `OnReactionsAddedAsync(IList\u003CMessageReaction>, ...)` | `OnMessageReactionsAdded(handler)` |\n| `OnReactionsRemovedAsync(IList\u003CMessageReaction>, ...)` | `OnMessageReactionsRemoved(handler)` |\n| `OnEventAsync(ITurnContext\u003CIEventActivity>, CT)` | `OnEvent(eventName, handler)` or `OnActivity(ActivityTypes.Event, handler)` |\n| `OnInvokeActivityAsync(...)` with `adaptiveCard\u002Faction` + verb switch | `AdaptiveCards.OnActionExecute(verb, handler)` — one registration per verb (preferred) |\n| `OnInvokeActivityAsync(...)` with `application\u002Fsearch` | `AdaptiveCards.OnSearch(dataset, handler)` — one registration per `choices.data.dataset` value |\n| `OnInvokeActivityAsync(...)` (other invoke types) | `OnActivity(ActivityTypes.Invoke, handler)` |\n| `OnTurnAsync(...)` override (cross-cutting) | `OnBeforeTurn(handler)` \u002F `OnAfterTurn(handler)` |\n| `OnInstallationUpdateActivityAsync(...)` | `OnActivity(ActivityTypes.InstallationUpdate, handler)` |\n| `OnEndOfConversationActivityAsync(...)` | `OnActivity(ActivityTypes.EndOfConversation, handler)` |\n\n**Key difference:** Handler signature changes from `(ITurnContext\u003CT>, CT)` to `(ITurnContext, ITurnState, CT)`.\n`membersAdded`, `membersRemoved`, `messageReactions` are no longer separate parameters — access via `turnContext.Activity.*`.\n\n### `adaptiveCard\u002Faction` invokes → `AdaptiveCards.OnActionExecute`\n\nIf the bot overrides `OnInvokeActivityAsync` and switches on a verb from `adaptiveCard\u002Faction` activities, replace it with per-verb `AdaptiveCards.OnActionExecute` registrations. `AdaptiveCards` is a property on `AgentApplication` (no `RegisterExtension` needed):\n\n```csharp\n\u002F\u002F Before: one OnInvokeActivityAsync with switch(verb)\nprotected override async Task\u003CInvokeResponse> OnInvokeActivityAsync(ITurnContext\u003CIInvokeActivity> ctx, CancellationToken ct)\n{\n    if (ctx.Activity.Name == \"adaptiveCard\u002Faction\")\n    {\n        var wrapper = JsonSerializer.Deserialize\u003CAdaptiveCardInvokeValue>(ctx.Activity.Value.ToString());\n        switch (wrapper.Action.Verb)\n        {\n            case \"approve\": return CreateInvokeResponse(GetApproveCard(wrapper.Action.Data));\n            case \"reject\":  return CreateInvokeResponse(GetRejectCard(wrapper.Action.Data));\n        }\n    }\n    return null;\n}\n\n\u002F\u002F After: one registration per verb — framework filters and extracts action.data\npublic MyBot(AgentApplicationOptions options) : base(options)\n{\n    AdaptiveCards.OnActionExecute(\"approve\", OnApproveAsync);\n    AdaptiveCards.OnActionExecute(\"reject\",  OnRejectedAsync);\n}\n\n\u002F\u002F Handler receives action.data directly — NOT the full AdaptiveCardInvokeValue\n\u002F\u002F Return AdaptiveCardInvokeResponse directly — no CreateInvokeResponse() wrapper\nprivate Task\u003CAdaptiveCardInvokeResponse> OnApproveAsync(\n    ITurnContext turnContext, ITurnState turnState, object data, CancellationToken ct)\n{\n    var actionData = ProtocolJsonSerializer.ToObject\u003CMyDataModel>(data);  \u002F\u002F data == action.data\n    return Task.FromResult(new AdaptiveCardInvokeResponse\n    {\n        StatusCode = 200,\n        Type = \"application\u002Fvnd.microsoft.card.adaptive\",\n        Value = BuildCard(actionData)\n    });\n}\n```\n\n**Key points:**\n- `data` parameter = `invokeValue.Action.Data` — deserialize as your data model, not as `AdaptiveCardInvokeValue`\n- Return `AdaptiveCardInvokeResponse` directly — the framework wraps it in an `InvokeResponse` automatically\n- `CreateInvokeResponse()` is a compat-layer helper that does not exist on `AgentApplication`\n- Namespace: `using Microsoft.Agents.Builder.App.AdaptiveCards;`\n\n---\n\n## Step 1-a: Convert Bot Class to AgentApplication (not using Dialogs)\n\n- Remove `using Microsoft.Agents.Builder.Compat;` (ActivityHandler namespace)\n- Remove `using Microsoft.Agents.Extensions.Teams.Compat;` (TeamsActivityHandler namespace)\n- Keep all other `using Microsoft.Agents.*` statements — they are already correct\n\n```csharp\n\u002F\u002F Before: ActivityHandler compat layer\nusing Microsoft.Agents.Builder.Compat;         \u002F\u002F REMOVE\nusing Microsoft.Agents.Extensions.Teams.Compat; \u002F\u002F REMOVE if Teams\nusing Microsoft.Agents.Builder;\nusing Microsoft.Agents.Core.Models;\n\npublic class EchoBot : ActivityHandler  \u002F\u002F or TeamsActivityHandler\n{\n    protected override async Task OnMessageActivityAsync(ITurnContext\u003CIMessageActivity> turnContext, CancellationToken ct)\n    { \u002F* business logic *\u002F\n    }\n}\n\n\u002F\u002F After: AgentApplication\nusing Microsoft.Agents.Builder;\nusing Microsoft.Agents.Builder.App;\nusing Microsoft.Agents.Core.Models;\n\npublic class EchoBot : AgentApplication\n{\n    public EchoBot(AgentApplicationOptions options) : base(options)\n    {\n        OnConversationUpdate(ConversationUpdateEvents.MembersAdded, OnMembersAddedAsync);\n        OnActivity(ActivityTypes.Message, OnMessageAsync, rank: RouteRank.Last);\n    }\n\n    \u002F\u002F Signature: (ITurnContext, ITurnState, CancellationToken)\n    private async Task OnMessageAsync(ITurnContext ctx, ITurnState state, CancellationToken ct)\n    { \u002F* same business logic *\u002F }\n}\n```\n\nFor Teams bots (`TeamsActivityHandler`) with Teams-specific handlers (messaging extensions, task modules, etc.), see **Step 1-d** below.\n\n## Step 1-b: Convert Bot Class to AgentApplication (using Dialogs)\n\n- Remove `using Microsoft.Agents.Builder.Compat;` (ActivityHandler namespace)\n- Remove `using Microsoft.Agents.Extensions.Teams.Compat;` (TeamsActivityHandler namespace)\n- Keep all other `using Microsoft.Agents.*` statements — they are already correct\n\n```csharp\n\u002F\u002F Before: ActivityHandler compat layer\nusing Microsoft.Agents.Builder.Compat;         \u002F\u002F REMOVE\nusing Microsoft.Agents.Builder;\nusing Microsoft.Agents.Builder.State;\nusing Microsoft.Agents.Core.Models;\n\npublic class EchoBot : ActivityHandler\n{\n    protected override Task OnMessageActivityAsync(ITurnContext\u003CIMessageActivity> turnContext, CancellationToken ct)\n        => dialog.RunAsync(turnContext, conversationState, ct);\n}\n\n\u002F\u002F After: AgentApplication\nusing Microsoft.Agents.Builder;\nusing Microsoft.Agents.Builder.App;\nusing Microsoft.Agents.Builder.State;\nusing Microsoft.Agents.Core.Models;\n\npublic class EchoBot : AgentApplication\n{\n    public EchoBot(AgentApplicationOptions options, MainDialog dialog) : base(options)\n    {\n        _dialog = dialog;\n        OnActivity(ActivityTypes.Message, OnMessageAsync, rank: RouteRank.Last);\n        \u002F\u002F signin\u002FverifyState and signin\u002FtokenExchange are both matched by \"signin\u002F.*\"\n        OnActivity(\n            (ctx, ct) => Task.FromResult(ctx.Activity.IsType(ActivityTypes.Invoke) && ctx.Activity.Name != null && Regex.IsMatch(ctx.Activity.Name, \"signin\u002F.*\")),\n            OnSigninInvokeStateAsync);\n    }\n\n    \u002F\u002F Signature: (ITurnContext, ITurnState, CancellationToken) — NOT the ActivityHandler signature\n    private Task OnMessageAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken ct)\n        => _dialog.RunAsync(turnContext, turnState.Conversation, ct);\n\n    private Task OnSigninInvokeStateAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken ct)\n        => _dialog.RunAsync(turnContext, turnState.Conversation, ct);\n}\n```\n\n**Key differences from non-dialog migration:**\n- Do **not** inject `ConversationState` into the bot — pass `turnState.Conversation` to `Dialog.RunAsync` instead\n- Use `InvokeRouteBuilder` (not `OnActivity(ActivityTypes.Invoke, ...)`) to route signin invokes — the name pattern matches both `signin\u002FverifyState` and `signin\u002FtokenExchange`\n- Remove `ConversationState` and `UserState` from DI entirely — see Step 2\n\n> ⚠️ **Generic `DialogBot\u003CT>` base class pattern:** Some projects use a two-level class hierarchy where a generic base class (e.g. `DialogBot\u003CT> : ActivityHandler`) holds the dialog field, state injection, and `OnTurnAsync` state-saving override, and the concrete bot class (e.g. `MyBot : DialogBot\u003CMainDialog>`) only adds routing. Collapse both classes into a single non-generic `AgentApplication` subclass — inject the concrete dialog type directly in the constructor. The generic type parameter is not needed. Remove `OnTurnAsync` entirely (AgentApplication manages state automatically).\n\n---\n\n## Step 1-c: Remove State Management Boilerplate\n\n### Remove OnTurnBeginAsync \u002F OnTurnEndAsync Overrides\n\n`ActivityHandler` and `TeamsActivityHandler` bots sometimes manually load and save state in turn lifecycle overrides. Remove these entirely — `AgentApplication` handles state loading and saving automatically:\n\n```csharp\n\u002F\u002F REMOVE these overrides completely — AgentApplication does this automatically\nprotected override async Task OnTurnBeginAsync(ITurnContext turnContext, CancellationToken cancellationToken = default)\n{\n    await ConversationState.LoadAsync(turnContext, false, cancellationToken);\n    await UserState.LoadAsync(turnContext, false, cancellationToken);\n}\n\nprotected override async Task OnTurnEndAsync(ITurnContext turnContext, CancellationToken cancellationToken = default)\n{\n    await ConversationState.SaveChangesAsync(turnContext, false, cancellationToken);\n    await UserState.SaveChangesAsync(turnContext, false, cancellationToken);\n}\n```\n\nAlso remove any `ConversationState` or `UserState` properties\u002Ffields that were injected for this purpose.\n\n### Migrate CloudAdapter OnTurnError to AgentApplication\n\nIf a custom `CloudAdapter` subclass injects `ConversationState` only to call `DeleteStateAsync` on error, move that logic to an `AgentApplication.OnTurnError` handler instead.\n\n**Before — in the custom adapter:**\n```csharp\npublic MyAdapter(\n    IChannelServiceClientFactory channelServiceClientFactory,\n    IActivityTaskQueue activityTaskQueue,\n    ILogger\u003CCloudAdapter> logger,\n    ConversationState conversationState)   \u002F\u002F REMOVE this parameter\n    : base(channelServiceClientFactory, activityTaskQueue, logger: logger)\n{\n    OnTurnError = async (turnContext, exception) =>\n    {\n        if (conversationState != null)\n        {\n            await conversationState.DeleteStateAsync(turnContext);  \u002F\u002F REMOVE\n        }\n    };\n}\n```\n\n**After — remove ConversationState from the adapter:**\n```csharp\npublic MyAdapter(\n    IChannelServiceClientFactory channelServiceClientFactory,\n    IActivityTaskQueue activityTaskQueue,\n    ILogger\u003CCloudAdapter> logger)\n    : base(channelServiceClientFactory, activityTaskQueue, logger: logger)\n{\n    \u002F\u002F OnTurnError can remain for logging; state deletion moves to AgentApplication\n}\n```\n\n**Add to the AgentApplication bot constructor:**\n```csharp\npublic MyBot(AgentApplicationOptions options, ...) : base(options)\n{\n    OnTurnError(OnAgentTurnErrorAsync);\n    \u002F\u002F ... other route registrations\n}\n\nprivate async Task OnAgentTurnErrorAsync(ITurnContext turnContext, ITurnState turnState, Exception exception, CancellationToken cancellationToken)\n{\n    try\n    {\n        await turnState.Conversation.DeleteStateAsync(turnContext, cancellationToken);\n    }\n    catch(Exception ex)\n    {\n        Logger.LogError(ex, \"Exception deleting conversation state after a turn error.\");\n    }\n}\n```\n\nCustomer-written classes that accept `ConversationState` or `UserState` as constructor parameters can remain unchanged for now. However, they will ultimately need to source their state from `ITurnState.Conversation` or `ITurnState.User` — flag this to the customer as a follow-up item.\n\n### `application\u002Fsearch` invokes → `AdaptiveCards.OnSearch`\n\nIf the bot overrides `OnInvokeActivityAsync` and handles `activity.Name == \"application\u002Fsearch\"` (adaptive card typeahead\u002Fdynamic search), replace it with per-dataset `AdaptiveCards.OnSearch` registrations. The dataset name comes from `choices.data.dataset` in the card JSON. The handler returns `IList\u003CAdaptiveCardsSearchResult>` — the framework automatically wraps results in the `application\u002Fvnd.microsoft.search.searchResponse` format and sends the invoke response.\n\n```csharp\n\u002F\u002F Before: one OnInvokeActivityAsync checking activity.Name\nprotected override async Task\u003CInvokeResponse> OnInvokeActivityAsync(ITurnContext\u003CIInvokeActivity> turnContext, CancellationToken ct)\n{\n    if (turnContext.Activity.Name == \"application\u002Fsearch\")\n    {\n        var searchData = JsonSerializer.Deserialize\u003CDynamicSearchCard>(turnContext.Activity.Value.ToString());\n        \u002F\u002F ... build results ...\n        return new InvokeResponse { Status = 200, Body = searchResponseData };\n    }\n    return null;\n}\n\n\u002F\u002F After: per-dataset OnSearch registrations\npublic ActivityBot(AgentApplicationOptions options) : base(options)\n{\n    AdaptiveCards.OnSearch(\"npmpackages\", OnNpmSearchAsync);\n    AdaptiveCards.OnSearch(\"cities\", OnCitiesSearchAsync);\n}\n\n\u002F\u002F Handler signature: (ITurnContext, ITurnState, Query\u003CAdaptiveCardsSearchParams>, CT) → Task\u003CIList\u003CAdaptiveCardsSearchResult>>\nprivate async Task\u003CIList\u003CAdaptiveCardsSearchResult>> OnNpmSearchAsync(\n    ITurnContext turnContext, ITurnState turnState, Query\u003CAdaptiveCardsSearchParams> query, CancellationToken ct)\n{\n    \u002F\u002F query.Parameters.QueryText = search text typed by user\n    \u002F\u002F query.Parameters.Dataset  = \"npmpackages\"\n    \u002F\u002F ... fetch results ...\n    return results.Select(r => new AdaptiveCardsSearchResult(r.Title, r.Value)).ToList();\n}\n```\n\n**Key differences:**\n- Return `IList\u003CAdaptiveCardsSearchResult>` directly — no `InvokeResponse` wrapper\n- `AdaptiveCardsSearchResult(string title, string value)` — constructor takes title and value\n- `query.Parameters.QueryText` replaces `searchData.queryText`\n- `query.Parameters.Dataset` contains the dataset name (same as the registration key)\n\n> ⚠️ **Dependent dropdown — associated inputs not in `query`:** When a card uses `\"associatedInputs\": \"auto\"`, the selected values of other inputs are sent in the `data` field of the raw invoke payload — NOT in `query.Parameters`. Access them directly: `ProtocolJsonSerializer.ToObject\u003CMyModel>(turnContext.Activity.Value)` where `MyModel` maps the top-level `data` field.\n>\n> ```csharp\n> private Task\u003CIList\u003CAdaptiveCardsSearchResult>> OnCitiesSearchAsync(\n>     ITurnContext turnContext, ITurnState turnState, Query\u003CAdaptiveCardsSearchParams> query, CancellationToken ct)\n> {\n>     \u002F\u002F Associated input (country selector) arrives in activity.Value's \"data\" field\n>     var card = ProtocolJsonSerializer.ToObject\u003CDependantDropdownCard>(turnContext.Activity.Value);\n>     string country = card?.data?.choiceSelect?.ToLower() ?? \"\";\n>     \u002F\u002F ... return cities for country ...\n> }\n> ```\n\n---\n\n## Step 1-d: Convert TeamsActivityHandler with Teams-Specific Handlers\n\nFor bots that override Teams-specific methods (messaging extensions, task modules, etc.), use `RegisterExtension(new TeamsAgentExtension(this), ...)` inside the constructor.\n\n### TeamsActivityHandler → TeamsAgentExtension handler mapping\n\n**Message Extensions** — handlers return `Task\u003CMessagingExtensionResult>` (not `MessagingExtensionResponse`):\n\n| TeamsActivityHandler Override | TeamsAgentExtension Registration | Handler Delegate |\n|-------------------------------|----------------------------------|-----------------|\n| `OnTeamsMessagingExtensionQueryAsync(ctx, MessagingExtensionQuery, CT)` | `teams.MessageExtensions.OnQuery(commandId, handler)` | `(ITurnContext, ITurnState, Query\u003CIDictionary\u003Cstring,object>>, CT) → Task\u003CMessagingExtensionResult>` |\n| `OnTeamsMessagingExtensionSelectItemAsync(ctx, JsonElement, CT)` | `teams.MessageExtensions.OnSelectItem(handler)` | `(ITurnContext, ITurnState, object item, CT) → Task\u003CMessagingExtensionResult>` |\n| `OnTeamsAppBasedLinkQueryAsync(ctx, AppBasedLinkQuery, CT)` | `teams.MessageExtensions.OnQueryLink(handler)` | `(ITurnContext, ITurnState, string url, CT) → Task\u003CMessagingExtensionResult>` |\n| `OnTeamsAnonymousAppBasedLinkQueryAsync(ctx, AppBasedLinkQuery, CT)` | `teams.MessageExtensions.OnAnonymousQueryLink(handler)` | `(ITurnContext, ITurnState, string url, CT) → Task\u003CMessagingExtensionResult>` |\n| `OnTeamsMessagingExtensionFetchTaskAsync(ctx, MessagingExtensionAction, CT)` | `teams.MessageExtensions.OnFetchTask(commandId, handler)` | `(ITurnContext, ITurnState, CT) → Task\u003CTaskModuleResponse>` |\n| `OnTeamsMessagingExtensionSubmitActionAsync(ctx, MessagingExtensionAction, CT)` | `teams.MessageExtensions.OnSubmitAction(commandId, handler)` | `(ITurnContext, ITurnState, object data, CT) → Task\u003CMessagingExtensionActionResponse>` |\n| `OnTeamsMessagingExtensionAgentMessagePreviewEditAsync(ctx, MessagingExtensionAction, CT)` | `teams.MessageExtensions.OnAgentMessagePreviewEdit(commandId, handler)` | `(ITurnContext, ITurnState, IActivity activityPreview, CT) → Task\u003CMessagingExtensionActionResponse>` |\n| `OnTeamsMessagingExtensionAgentMessagePreviewSendAsync(ctx, MessagingExtensionAction, CT)` | `teams.MessageExtensions.OnAgentMessagePreviewSend(commandId, handler)` | `(ITurnContext, ITurnState, IActivity activityPreview, CT) → Task` |\n| `OnTeamsMessagingExtensionConfigurationQuerySettingUrlAsync(ctx, MessagingExtensionQuery, CT)` | `teams.MessageExtensions.OnQueryUrlSetting(handler)` | `(ITurnContext, ITurnState, CT) → Task\u003CMessagingExtensionResult>` |\n| `OnTeamsMessagingExtensionConfigurationSettingAsync(ctx, JsonElement, CT)` | `teams.MessageExtensions.OnConfigureSettings(handler)` | `(ITurnContext, ITurnState, object settings, CT) → Task` |\n| `OnTeamsMessagingExtensionCardButtonClickedAsync(ctx, JsonElement, CT)` | `teams.MessageExtensions.OnCardButtonClicked(handler)` | `(ITurnContext, ITurnState, object cardData, CT) → Task` |\n\n**Task Modules:**\n\n| TeamsActivityHandler Override | TeamsAgentExtension Registration | Handler Delegate |\n|-------------------------------|----------------------------------|-----------------|\n| `OnTeamsTaskModuleFetchAsync(ctx, TaskModuleRequest, CT)` | `teams.TaskModules.OnFetch(verb, handler)` | `(ITurnContext, ITurnState, object data, CT) → Task\u003CTaskModuleResponse>` |\n| `OnTeamsTaskModuleSubmitAsync(ctx, TaskModuleRequest, CT)` | `teams.TaskModules.OnSubmit(verb, handler)` | `(ITurnContext, ITurnState, object data, CT) → Task\u003CTaskModuleResponse>` |\n\n**⚠️ Task Module verb matching:** `OnFetch` and `OnSubmit` match by looking for a `verb` field inside `activity.Value.data`. If the submitted data has **no `verb` field**, use the `RouteSelector` overload instead:\n\n```csharp\nteams.TaskModules.OnSubmit(\n    (ctx, ct) => Task.FromResult(\n        string.Equals(ctx.Activity.Type, ActivityTypes.Invoke, StringComparison.OrdinalIgnoreCase) &&\n        string.Equals(ctx.Activity.Name, \"task\u002Fsubmit\", StringComparison.OrdinalIgnoreCase)),\n    OnTaskModuleSubmitAsync);\n```\n\n**⚠️ `data` parameter in submit handler:** The `data` parameter passed to `SubmitHandlerAsync` is `taskModuleAction.Value` from a `CardAction` deserialization of the payload. For `task\u002Fsubmit` payloads where the top-level JSON has no `\"value\"` key (only `\"data\"` and `\"context\"`), this will be `null`. Access the submitted data via `turnContext.Activity.Value` directly:\n\n```csharp\nprivate async Task\u003CTaskModuleResponse> OnTaskModuleSubmitAsync(\n    ITurnContext turnContext, ITurnState turnState, object data, CancellationToken cancellationToken)\n{\n    \u002F\u002F data parameter is null when payload has no top-level \"value\" key — use Activity.Value instead\n    var request = ProtocolJsonSerializer.ToObject\u003CTaskModuleRequest>(turnContext.Activity.Value);\n    var feedback = ProtocolJsonSerializer.ToObject\u003CMySubmitModel>(request.Data);\n    \u002F\u002F ...\n    return null; \u002F\u002F null dismisses the task module\n}\n```\n\n**Meetings:**\n\n| TeamsActivityHandler Override | TeamsAgentExtension Registration | Handler Delegate |\n|-------------------------------|----------------------------------|-----------------|\n| `OnTeamsMeetingStartAsync(MeetingStartEventDetails, ctx, CT)` | `teams.Meetings.OnStart(handler)` | `(ITurnContext, ITurnState, MeetingStartEventDetails, CT) → Task` |\n| `OnTeamsMeetingEndAsync(MeetingEndEventDetails, ctx, CT)` | `teams.Meetings.OnEnd(handler)` | `(ITurnContext, ITurnState, MeetingEndEventDetails, CT) → Task` |\n| `OnTeamsMeetingParticipantsJoinAsync(MeetingParticipantsEventDetails, ctx, CT)` | `teams.Meetings.OnParticipantsJoin(handler)` | `(ITurnContext, ITurnState, MeetingParticipantsEventDetails, CT) → Task` |\n| `OnTeamsMeetingParticipantsLeaveAsync(MeetingParticipantsEventDetails, ctx, CT)` | `teams.Meetings.OnParticipantsLeave(handler)` | `(ITurnContext, ITurnState, MeetingParticipantsEventDetails, CT) → Task` |\n\n**Messages (edit\u002Fdelete):**\n\n| TeamsActivityHandler Override | TeamsAgentExtension Registration |\n|-------------------------------|----------------------------------|\n| `OnTeamsMessageEditAsync(ctx, CT)` | `teams.OnMessageEdit(handler)` |\n| `OnTeamsMessageUndeleteAsync(ctx, CT)` | `teams.OnMessageUndelete(handler)` |\n| `OnTeamsMessageSoftDeleteAsync(ctx, CT)` | `teams.OnMessageDelete(handler)` |\n| `OnTeamsReadReceiptAsync(ReadReceiptInfo, ctx, CT)` | `teams.OnTeamsReadReceipt(handler)` |\n\n**File Consent:**\n\n| TeamsActivityHandler Override | TeamsAgentExtension Registration |\n|-------------------------------|----------------------------------|\n| `OnTeamsFileConsentAcceptAsync(ctx, FileConsentCardResponse, CT)` | `teams.OnFileConsentAccept(handler)` |\n| `OnTeamsFileConsentDeclineAsync(ctx, FileConsentCardResponse, CT)` | `teams.OnFileConsentDecline(handler)` |\n\n**Bot Config:**\n\n| TeamsActivityHandler Override | TeamsAgentExtension Registration |\n|-------------------------------|----------------------------------|\n| `OnTeamsConfigFetchAsync(ctx, JsonElement, CT)` | `teams.OnConfigFetch(handler)` |\n| `OnTeamsConfigSubmitAsync(ctx, JsonElement, CT)` | `teams.OnConfigSubmit(handler)` |\n\n**Channels, Teams, Members** — all route through `teams.OnConversationUpdate(eventName, handler)` with constants from `TeamsConversationUpdateEvents`:\n\n| TeamsActivityHandler Override | Event Constant |\n|-------------------------------|----------------|\n| `OnTeamsMembersAddedAsync` | `ConversationUpdateEvents.MembersAdded` |\n| `OnTeamsMembersRemovedAsync` | `ConversationUpdateEvents.MembersRemoved` |\n| `OnTeamsChannelCreatedAsync` | `TeamsConversationUpdateEvents.ChannelCreated` |\n| `OnTeamsChannelDeletedAsync` | `TeamsConversationUpdateEvents.ChannelDeleted` |\n| `OnTeamsChannelRenamedAsync` | `TeamsConversationUpdateEvents.ChannelRenamed` |\n| `OnTeamsChannelRestoredAsync` | `TeamsConversationUpdateEvents.ChannelRestored` |\n| `OnTeamsTeamArchivedAsync` | `TeamsConversationUpdateEvents.TeamArchived` |\n| `OnTeamsTeamUnarchivedAsync` | `TeamsConversationUpdateEvents.TeamUnarchived` |\n| `OnTeamsTeamDeletedAsync` | `TeamsConversationUpdateEvents.TeamDeleted` |\n| `OnTeamsTeamHardDeletedAsync` | `TeamsConversationUpdateEvents.TeamHardDeleted` |\n| `OnTeamsTeamRenamedAsync` | `TeamsConversationUpdateEvents.TeamRenamed` |\n| `OnTeamsTeamRestoredAsync` | `TeamsConversationUpdateEvents.TeamRestored` |\n\n**Other:**\n\n| TeamsActivityHandler Override | TeamsAgentExtension Registration |\n|-------------------------------|----------------------------------|\n| `OnTeamsO365ConnectorCardActionAsync(ctx, O365ConnectorCardActionQuery, CT)` | `teams.OnO365ConnectorCardAction(handler)` |\n| `OnTeamsSigninVerifyStateAsync(ctx, CT)` | On `AgentApplication` directly: `OnActivity((ctx, ct) => Task.FromResult(ctx.Activity.IsType(ActivityTypes.Invoke) && Regex.IsMatch(ctx.Activity.Name, \"signin\u002F.*\")), handler)` |\n| `OnTeamsTabFetchAsync(ctx, TabRequest, CT)` | No direct equivalent — use `OnActivity(ActivityTypes.Invoke, handler)` with a name filter |\n| `OnTeamsTabSubmitAsync(ctx, TabSubmit, CT)` | No direct equivalent — use `OnActivity(ActivityTypes.Invoke, handler)` with a name filter |\n\n### Handler signature changes\n\n**Query handler** — return type changes from `Task\u003CMessagingExtensionResponse>` to `Task\u003CMessagingExtensionResult>`:\n```csharp\n\u002F\u002F Before\nprotected override async Task\u003CMessagingExtensionResponse> OnTeamsMessagingExtensionQueryAsync(\n    ITurnContext\u003CIInvokeActivity> turnContext, MessagingExtensionQuery query, CancellationToken ct)\n{\n    var text = query?.Parameters?[0]?.Value?.ToString();  \u002F\u002F index-based parameter access\n    \u002F\u002F ...\n    return new MessagingExtensionResponse { ComposeExtension = new MessagingExtensionResult { ... } };\n}\n\n\u002F\u002F After — registered as: teams.MessageExtensions.OnQuery(\"commandId\", OnQueryAsync)\nprivate async Task\u003CMessagingExtensionResult> OnQueryAsync(\n    ITurnContext turnContext, ITurnState turnState,\n    Query\u003CIDictionary\u003Cstring, object>> query, CancellationToken ct)\n{\n    \u002F\u002F Named parameter access — value is a JsonElement\n    string text = string.Empty;\n    if (query.Parameters.TryGetValue(\"paramName\", out var val) && val is JsonElement el)\n        text = el.GetString() ?? string.Empty;\n    \u002F\u002F ...\n    return new MessagingExtensionResult { Type = \"result\", AttachmentLayout = \"list\", Attachments = attachments };\n    \u002F\u002F NOTE: return MessagingExtensionResult directly — no MessagingExtensionResponse wrapper\n}\n```\n\n**SelectItem handler** — `item` is now `object` (cast to `JsonElement`):\n```csharp\n\u002F\u002F Before\nprotected override Task\u003CMessagingExtensionResponse> OnTeamsMessagingExtensionSelectItemAsync(\n    ITurnContext\u003CIInvokeActivity> turnContext, JsonElement query, CancellationToken ct)\n{\n    string id = query.GetProperty(\"packageId\").GetString();\n    return Task.FromResult(new MessagingExtensionResponse { ComposeExtension = new MessagingExtensionResult { ... } });\n}\n\n\u002F\u002F After — registered as: teams.MessageExtensions.OnSelectItem(OnSelectItemAsync)\nprivate Task\u003CMessagingExtensionResult> OnSelectItemAsync(\n    ITurnContext turnContext, ITurnState turnState, object item, CancellationToken ct)\n{\n    JsonElement query = (JsonElement)item;\n    string id = query.GetProperty(\"packageId\").GetString();\n    return Task.FromResult(new MessagingExtensionResult { Type = \"result\", ... });\n    \u002F\u002F NOTE: return MessagingExtensionResult directly — no MessagingExtensionResponse wrapper\n}\n```\n\n### Full registration pattern\n\n```csharp\nusing Microsoft.Agents.Builder.App;             \u002F\u002F AgentApplication\nusing Microsoft.Agents.Builder.App.AdaptiveCards; \u002F\u002F Query\u003CT>\nusing Microsoft.Agents.Builder.State;            \u002F\u002F ITurnState\nusing Microsoft.Agents.Extensions.Teams.App;    \u002F\u002F TeamsAgentExtension\nusing Microsoft.Agents.Extensions.Teams.Models; \u002F\u002F MessagingExtensionResult, etc.\n\u002F\u002F REMOVE: using Microsoft.Agents.Extensions.Teams.Compat;\n\npublic class MyTeamsBot : AgentApplication\n{\n    public MyTeamsBot(AgentApplicationOptions options) : base(options)\n    {\n        RegisterExtension(new TeamsAgentExtension(this), teams =>\n        {\n            teams.MessageExtensions.OnQuery(\"searchCommandId\", OnQueryAsync);\n            teams.MessageExtensions.OnSelectItem(OnSelectItemAsync);\n        });\n    }\n}\n```\n\n**Key differences:**\n- Helper methods that returned `MessagingExtensionResponse` must be changed to return `MessagingExtensionResult` — drop the outer `new MessagingExtensionResponse { ComposeExtension = ... }` wrapper\n- `MessagingExtensionQuery.Parameters[index].Value` → `Query\u003CIDictionary\u003Cstring,object>>.Parameters.TryGetValue(\"name\", out var val)` where `val` is a `JsonElement`\n- `commandId` in `OnQuery(commandId, ...)` must match the command `id` in the Teams app manifest\n\n---\n\n## Step 2: Update Program.cs\n\n### Add `AddAgentApplicationOptions`\n\nAdd this call **before** `builder.AddAgent\u003CT>()` — it is required for `AgentApplication` and was absent in ActivityHandler-based bots:\n\n```csharp\nbuilder.AddAgentApplicationOptions();  \u002F\u002F ADD THIS — required for AgentApplication\nbuilder.AddAgent\u003CEchoBot>();           \u002F\u002F existing line — keep\n```\n\n### Ensure IStorage Is Registered\n\n`AgentApplication` always requires an `IStorage` registration — even if the bot has no dialogs or explicit state usage. If it is not already present, add it:\n\n```csharp\nbuilder.Services.AddSingleton\u003CIStorage, MemoryStorage>(); \u002F\u002F always required by AgentApplication\n```\n\n### Remove ConversationState and UserState from DI\n\n`AgentApplication` manages state internally via `ITurnState`. Remove these registrations entirely:\n\n```csharp\n\u002F\u002F REMOVE both of these — AgentApplication does not use them\n\u002F\u002F builder.Services.AddSingleton\u003CConversationState>();\n\u002F\u002F builder.Services.AddSingleton\u003CUserState>();\n\nbuilder.Services.AddSingleton\u003CIStorage, MemoryStorage>(); \u002F\u002F keep — required by AgentApplication\nbuilder.Services.AddSingleton\u003CMainDialog>();               \u002F\u002F keep — dialog class itself is still needed\nbuilder.Services.AddSingleton\u003CIMyService, MyService>();    \u002F\u002F keep all custom services\n```\n\n### Preserve All Other Custom DI\n\nKeep dialogs, storage, adapters, and custom services. Only `ConversationState` and `UserState` are removed.\n\n### TeamsSSOTokenExchangeMiddleware\n\nIf the ActivityHandler bot registered `TeamsSSOTokenExchangeMiddleware`, **remove it** — it is not required and should not be used with `AgentApplication`. Remove it from DI and from any `IMiddleware[]` array registration.\n\n---\n\n## Step 3: Update Endpoint Mapping\n\nIdentify which endpoint pattern the existing bot uses, then apply the corresponding change.\n\n### Pattern A: `app.MapControllers()` + `BotController.cs` (most common in Agents SDK compat samples)\n\n```csharp\n\u002F\u002F Before Program.cs\nbuilder.Services.AddControllers();           \u002F\u002F needed for MapControllers\n\u002F\u002F ...\napp.MapControllers().AllowAnonymous();       \u002F\u002F dev\napp.MapControllers();                        \u002F\u002F prod\n\n\u002F\u002F After Program.cs\n\u002F\u002F Remove AddControllers() ONLY IF no other MVC controllers exist in the project\n\u002F\u002F Add authentication middleware if not already present:\napp.UseAuthentication();\napp.UseAuthorization();\napp.MapAgentRootEndpoint();                                              \u002F\u002F optional GET \"\u002F\"\napp.MapAgentApplicationEndpoints(requireAuth: !app.Environment.IsDevelopment());\n```\n\nDelete `BotController.cs`. Check first that it contains no custom logic beyond calling `adapter.ProcessAsync` — if it does, preserve that logic.\n\n**If the project uses Razor Pages** (`AddRazorPages()` \u002F `MapRazorPages()`): keep both — they serve web UI pages unrelated to the bot endpoint. Remove `AddControllers()`, `AddMvc()`, and any `MapControllerRoute()` \u002F `MapControllers()` calls, but leave the Razor Pages registrations in place:\n\n```csharp\n\u002F\u002F Keep — serves Razor Pages for web UI\nbuilder.Services.AddRazorPages();\n\u002F\u002F ...\napp.UseAuthentication();\napp.UseAuthorization();\napp.MapRazorPages();                   \u002F\u002F keep\napp.MapAgentRootEndpoint();\napp.MapAgentApplicationEndpoints(requireAuth: !app.Environment.IsDevelopment());\n```\n\nAlso remove the dev branch `app.MapControllers().AllowAnonymous()` pattern — auth is now handled by `requireAuth` on `MapAgentApplicationEndpoints`.\n\n### Pattern B: `app.MapAgentEndpoints()`\n\n```csharp\n\u002F\u002F Before\napp.MapAgentEndpoints(requireAuth: !app.Environment.IsDevelopment());\n\n\u002F\u002F After\napp.MapAgentRootEndpoint();\napp.MapAgentApplicationEndpoints(requireAuth: !app.Environment.IsDevelopment());\n```\n\n### Pattern C: `app.MapPost(...)` (older minimal API)\n\nOffer to switch. If accepted:\n\n```csharp\n\u002F\u002F Remove:\napp.MapPost(\"\u002Fapi\u002Fmessages\", async (HttpRequest req, HttpResponse res, IAgentHttpAdapter adapter, IAgent bot, CancellationToken ct)\n    => await adapter.ProcessAsync(req, res, bot, ct)).AllowAnonymous();\n\n\u002F\u002F Add:\napp.UseAuthentication();\napp.UseAuthorization();\napp.MapAgentRootEndpoint();\napp.MapAgentApplicationEndpoints(requireAuth: !app.Environment.IsDevelopment());\n```\n\n### Step 4 or at the very end of the migration:  Ask user if they would like to write the learnings from this migration to a markdown file they could submit to use to help us improve the skill.\n\n---\n\n## Development URL\n\nIf the existing bot had `app.Urls.Add(\"http:\u002F\u002Flocalhost:3978\")` inside an `IsDevelopment()` check, keep it. If it was missing, add it:\n\n```csharp\nif (app.Environment.IsDevelopment())\n{\n    app.Urls.Add(\"http:\u002F\u002Flocalhost:3978\");\n}\n```\n\n---\n\n## Middleware Replacements\n\nSome Bot Framework middleware has a direct equivalent in AgentApplication configuration.\n\n### ShowTypingMiddleware → StartTypingTimer\n\nDrop the `ShowTypingMiddleware` registration and enable the built-in typing timer instead:\n\n```csharp\n\u002F\u002F Remove from adapter setup:\n\u002F\u002F adapter.Use(new ShowTypingMiddleware());\n```\n\n```json\n\u002F\u002F appsettings.json — add to AgentApplication section:\n\"AgentApplication\": {\n  \"StartTypingTimer\": true\n}\n```\n\n### AutoSaveStateMiddleware\n\n`AgentApplication` loads and saves state automatically on every turn. **Always remove `AutoSaveStateMiddleware`** — it is no longer needed and must not be used with `AgentApplication`.\n\n```csharp\n\u002F\u002F REMOVE — always:\n\u002F\u002F new AutoSaveStateMiddleware(...)\n\u002F\u002F adapter.Use(new AutoSaveStateMiddleware(...));\n```\n\nIf removing it empties the `IMiddleware[]` DI registration, remove that registration entirely as well.\n\n### NormalizeMentionsMiddleware → NormalizeMentions \u002F RemoveRecipientMention\n\nDrop the `NormalizeMentionsMiddleware` registration and enable the equivalent settings instead:\n\n```csharp\n\u002F\u002F Remove from adapter setup:\n\u002F\u002F adapter.Use(new NormalizeMentionsMiddleware());\n```\n\n```json\n\u002F\u002F appsettings.json — add to AgentApplication section:\n\"AgentApplication\": {\n  \"NormalizeMentions\": true,\n  \"RemoveRecipientMention\": true\n}\n```\n\n---\n\n## Files to Delete\n\n| File | When to delete |\n|------|----------------|\n| `BotController.cs` | Always when switching to `MapAgentApplicationEndpoints` — unless it has custom logic beyond `ProcessAsync` |\n| `Controllers\u002F` folder | After deleting `BotController.cs`, if no other controllers remain |\n\nDo **not** delete `AspNetExtensions.cs` — if present it is providing the `AddAgentAspNetAuthentication` extension and must be kept.\n\n---\n\n## Common Mistakes\n\n| Mistake | Fix |\n|---------|-----|\n| Forgot `builder.AddAgentApplicationOptions()` | Add before `builder.AddAgent\u003CT>()` |\n| Removed custom DI (dialogs, state, services) | Restore — never remove developer-added registrations |\n| Added `[Agent]` attribute to AgentApplication class | Not required — `MapAgentApplicationEndpoints` discovers `AgentApplication` subclasses without it |\n| Left `using Microsoft.Agents.Builder.Compat` | Remove — ActivityHandler is gone |\n| Left `using Microsoft.Agents.Extensions.Teams.Compat` on main class | Remove — TeamsActivityHandler is gone; use `RegisterExtension(new TeamsAgentExtension(this), ...)` instead |\n| Teams MessageExtension handler returns `MessagingExtensionResponse` | Change return type to `MessagingExtensionResult` — the framework no longer uses the `ComposeExtension` wrapper; return the inner result directly |\n| Teams query parameter accessed by index (`query.Parameters[0].Value`) | Use named access: `query.Parameters.TryGetValue(\"paramName\", out var val)` where `val` is a `JsonElement`; parameter name comes from the Teams app manifest command definition |\n| Teams SelectItem handler uses `JsonElement` parameter | In `OnSelectItem`, the parameter type is `object`; cast it: `JsonElement query = (JsonElement)item` |\n| Missing `Microsoft.Agents.Extensions.Teams.App` namespace for TeamsAgentExtension | Add `using Microsoft.Agents.Extensions.Teams.App;` — `TeamsAgentExtension` is not in the Compat namespace |\n| Missing `Microsoft.Agents.Builder.App.AdaptiveCards` namespace for `Query\u003CT>` | Add `using Microsoft.Agents.Builder.App.AdaptiveCards;` — required for `Query\u003CIDictionary\u003Cstring, object>>` handler parameter |\n| `AdaptiveCard` is ambiguous after adding `using Microsoft.Agents.Builder.App.AdaptiveCards` | Conflict with `AdaptiveCards.AdaptiveCard` from the AdaptiveCards NuGet package. Use an alias instead: `using AgentAdaptiveCards = Microsoft.Agents.Builder.App.AdaptiveCards;` then reference `AgentAdaptiveCards.Query\u003CIDictionary\u003Cstring, object>>` in the handler signature |\n| Kept `builder.Services.AddControllers()` but deleted all controllers | Remove — no longer needed without MVC controllers |\n| Missing `app.UseAuthentication()` \u002F `app.UseAuthorization()` after switching from MapControllers | Add them before `MapAgentApplicationEndpoints` |\n| Injected `ConversationState` into bot constructor for dialogs | Remove from bot — use `turnState.Conversation` in `Dialog.RunAsync` calls instead |\n| Left `ConversationState` registered in DI | Remove — AgentApplication manages state internally via `ITurnState` |\n| Left `UserState` registered in DI | Remove — AgentApplication does not use it |\n| Left `AutoSaveStateMiddleware` registered | Remove entirely — AgentApplication saves state automatically; never keep it |\n| Left `ConversationState` injected in custom adapter `OnTurnError` for `DeleteStateAsync` | Remove the parameter; move `DeleteStateAsync` into an `AgentApplication.OnTurnError` handler using `turnState.Conversation.DeleteStateAsync` |\n| Left `OnTurnBeginAsync`\u002F`OnTurnEndAsync` overrides that load\u002Fsave state | Remove entirely — AgentApplication handles this automatically |\n| Kept generic `DialogBot\u003CT>` base class as a separate file | Collapse both classes into a single non-generic `AgentApplication` subclass; inject the concrete dialog type directly; delete the generic base class file |\n| Left `TeamsSSOTokenExchangeMiddleware` in DI or `IMiddleware[]` | Remove — not required and should not be used with AgentApplication |\n| Manually calling `SaveChangesAsync` in AgentApplication handlers | Remove — state is saved automatically |\n| Left `ShowTypingMiddleware` registration | Drop it; set `\"AgentApplication\": { \"StartTypingTimer\": true }` in appsettings.json |\n| Left `NormalizeMentionsMiddleware` registration | Drop it; set `NormalizeMentions` and\u002For `RemoveRecipientMention` to `true` in `AgentApplication` appsettings |\n| Handler accesses `membersAdded` as a parameter | Use `turnContext.Activity.MembersAdded` instead — it is no longer passed as a parameter |\n| Used `ProjectReference` to local SDK source instead of NuGet packages | Always use NuGet packages — customers don't have access to the SDK source repo |\n| Custom adapter constructor uses `ILogger\u003CIAgentHttpAdapter>` | Change to `ILogger\u003CCloudAdapter>` — `CloudAdapter` base constructor requires the concrete type, not the interface |\n| Changed business logic during migration | Do not — only change structure\u002Fregistration\u002Frouting |\n| Missing `IStorage` registration | Add `builder.Services.AddSingleton\u003CIStorage, MemoryStorage>();` — always required by AgentApplication, not just for dialog bots |\n| Used `OnActivity(ActivityTypes.Invoke, ...)` for `adaptiveCard\u002Faction` verbs | Use `AdaptiveCards.OnActionExecute(verb, handler)` instead — it's built into `AgentApplication`, matches by verb, and handles the invoke response automatically |\n| Called `CreateInvokeResponse(...)` in an `OnActionExecute` handler | `CreateInvokeResponse` is a compat-layer helper — it doesn't exist on `AgentApplication`. Return `AdaptiveCardInvokeResponse` directly; the framework wraps it |\n| Deserialized `data` as `AdaptiveCardInvokeValue` in `OnActionExecute` handler | The `data` parameter is already `invokeValue.Action.Data` — deserialize directly as your data model, not as the full invoke value wrapper |\n| `teams.TaskModules.OnSubmit(verb, ...)` never triggers | Default filter matches `activity.Value.data.verb` — if the submitted data has no `verb` field, use the `RouteSelector` overload with a custom selector that checks `ctx.Activity.Name == \"task\u002Fsubmit\"` |\n| `data` parameter is null in `SubmitHandlerAsync` | The `data` parameter is `taskModuleAction.Value` (CardAction), which is null when the payload has no top-level `\"value\"` key. Parse the submitted data directly: `ProtocolJsonSerializer.ToObject\u003CTaskModuleRequest>(turnContext.Activity.Value).Data` |\n| Removed `AddRazorPages()` \u002F `MapRazorPages()` when deleting BotController | Keep them — they serve web UI pages unrelated to the bot; only remove `AddControllers()`, `AddMvc()`, and `MapControllers()`\u002F`MapControllerRoute()` |\n| Used `OnActivity(ActivityTypes.Invoke, ...)` for `application\u002Fsearch` | Use `AdaptiveCards.OnSearch(dataset, handler)` instead — routes by `choices.data.dataset` value, handles invoke response automatically, handler returns `IList\u003CAdaptiveCardsSearchResult>` |\n| `OnSearch` handler returns `InvokeResponse` | Return `IList\u003CAdaptiveCardsSearchResult>` — the framework wraps results in `application\u002Fvnd.microsoft.search.searchResponse` and sends the invoke response |\n| Looked for associated input values (dependent dropdown) in `query.Parameters` | Associated inputs from `\"associatedInputs\": \"auto\"` arrive in the `data` field of the raw invoke payload, not in `query.Parameters`. Read them via `ProtocolJsonSerializer.ToObject\u003CMyModel>(turnContext.Activity.Value)` |\n",{"name":5,"description":7},"main","8171bc7e0ca3b8defd578a6bb317367c2901983f","agent-plugins\u002Fagents-for-net\u002Fskills\u002Fagents-sdk-dotnet-activityhandler-migration",346,"https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002FAgents","https:\u002F\u002Faka.ms\u002Fagentsdkdocs","https:\u002F\u002Fgithub.com\u002Fmicrosoft","https:\u002F\u002Fopensource.microsoft.com","Open source projects and samples from Microsoft","2026-11-14 08:54:12",{"source":9,"skillName":5,"commands":52,"prompt":62,"zipAvailable":63},[53,56,59],{"tool":54,"command":55},"npx","npx skills add microsoft\u002FAgents --skill agents-sdk-dotnet-activityhandler-migration",{"tool":57,"command":58},"bunx","bunx skills add microsoft\u002FAgents --skill agents-sdk-dotnet-activityhandler-migration",{"tool":60,"command":61},"pnpm","pnpm dlx skills add microsoft\u002FAgents --skill agents-sdk-dotnet-activityhandler-migration","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002FAgents\u002Fblob\u002Fmain\u002Fagent-plugins\u002Fagents-for-net\u002Fskills\u002Fagents-sdk-dotnet-activityhandler-migration\u002FSKILL.md",true,[],[66,84,104,120,138,151],{"skillNo":67,"name":68,"nameZh":17,"description":69,"descriptionZh":17,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":70,"categories":71,"keywords":72,"publishedAt":36},"01M6PJCYCYJQDX318SQN3EBF0E","sync-teams-samples-to-agents-sdk","CI instructions for a bounded Teams SDK to Agents SDK sample synchronization using the selected language profile.","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002FAgents\u002Fblob\u002Fmain\u002Fautomation\u002Fteams-sample-sync\u002Fskills\u002Fsync-teams-samples-to-agents-sdk\u002FSKILL.md",[],[31,32,73,74,75,76,77,78,79,80,81,82,83],"sync","teams","sync teams samples to agents sdk","ci","synchronization","instructions","profile","language","sample","for","bounded",{"skillNo":85,"name":86,"nameZh":17,"description":87,"descriptionZh":17,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":36},"01M6PJCFNGCX555YERYQ459JFE","teams-sdk-to-agents-sdk-typescript-migration","Migrate a JavaScript or TypeScript application using the Microsoft Teams SDK App runtime to Microsoft 365 Agents SDK while preserving its Teams behaviors. Use for Teams SDK migrations, including automated sample synchronization; use the separate Bot Framework migration skill for botbuilder applications.","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002FAgents\u002Fblob\u002Fmain\u002Fagent-plugins\u002Fagents-for-js\u002Fskills\u002Fteams-sdk-to-agents-sdk-typescript-migration\u002FSKILL.md",[],[74,91,31,32,92,93,94,95,96,97,98,81,99,100,77,101,82,102,103,10],"typescript","agents sdk typescript","migration","teams sdk to agents sdk typescript migration","microsoft teams","applications","app","runtime","migrations","use","migrate","bot","javascript",{"skillNo":105,"name":106,"nameZh":107,"description":108,"descriptionZh":109,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":110,"categories":111,"keywords":116,"publishedAt":36},"01M69B8QV24JVPXH25EH77X0SZ","teams-app-manifest","Teams 应用清单创建与审核","Create or audit a Microsoft Teams app manifest for an existing Microsoft 365 Agents SDK application by mapping declared intent and source-code evidence to released manifest capabilities. Use when manifest.json is missing, incomplete, or must be checked against implemented Teams features. Does not configure Microsoft Entra, Azure Bot, Developer Portal, or deployment unless separately requested.","为现有的 Microsoft 365 Agents SDK 应用程序创建或审核 Microsoft Teams 应用清单，方法是将声明的意图和源代码证据映射到已发布清单所支持的能力。适用于 manifest.json 缺失、不完整，或需要对照已实现的 Teams 功能进行核查的情况。除非另行要求，否则不配置 Microsoft Entra、Azure Bot、开发者门户（Developer Portal）或部署。","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002FAgents\u002Fblob\u002Fmain\u002Fagent-plugins\u002Fagents-sdk-common\u002Fskills\u002Fteams-app-manifest\u002FSKILL.md",[112,113],{"categoryNo":21,"categoryName":22,"taxonomyType":23,"taxonomyTypeDesc":24},{"categoryNo":114,"categoryName":115,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8BSAA4FBTWZP6X98STEHG99","智能体开发",[74,117,32,102,31,10,118,119],"teams app manifest","azure","deployment",{"skillNo":121,"name":122,"nameZh":123,"description":124,"descriptionZh":125,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":126,"categories":127,"keywords":132,"publishedAt":36},"01M69B8MN62NBY93YTJAQG2Y81","agents-sdk-provision","Agents SDK Azure 资源预配","Use when provisioning Azure resources for a Microsoft Agents SDK application — including creating an Azure Bot Service resource, setting up Entra app registrations, configuring identity credentials (UserManagedIdentity, FederatedCredentials, or ClientSecret), adding a Teams channel, running Bicep deployments for SSO, or setting up OAuth user sign-in connections via az CLI. Trigger even if the user doesn't say \"provision\" — use on requests like \"set up my bot on Azure\", \"deploy my bot\", \"configure Azure for my bot\", or \"get Teams SSO working.\" Applies to all languages (dotnet, Node.js, Python).","在为 Microsoft Agents SDK 应用预配 Azure 资源时使用——包括创建 Azure Bot Service 资源、设置 Entra 应用注册、配置身份凭据（UserManagedIdentity、FederatedCredentials 或 ClientSecret）、添加 Teams 频道、运行 Bicep 部署以实现 SSO，或通过 az CLI 设置 OAuth 用户登录连接。即使用户没有说“预配”也应触发——在诸如“在 Azure 上搭建我的机器人”“部署我的机器人”“为我的机器人配置 Azure”“让 Teams SSO 跑起来”等请求时使用。适用于所有语言（dotnet、Node.js、Python）。","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002FAgents\u002Fblob\u002Fmain\u002Fagent-plugins\u002Fagents-sdk-common\u002Fskills\u002Fagents-sdk-provision\u002FSKILL.md",[128,131],{"categoryNo":129,"categoryName":130,"taxonomyType":23,"taxonomyTypeDesc":24},"01M8BRZZF9D7PVFN5MXSPWWD61","AI 工程师",{"categoryNo":114,"categoryName":115,"taxonomyType":28,"taxonomyTypeDesc":29},[31,32,133,102,134,135,10,33,136,137,118,74],"agents sdk provision","cli","python","identity","deploy",{"skillNo":139,"name":140,"nameZh":141,"description":142,"descriptionZh":143,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":144,"categories":145,"keywords":148,"publishedAt":36},"01M69B8HFZ45NQGWQQD483TWPB","agents-sdk-to-prod","Agents SDK 智能体生产加固","Assess, create, harden, deploy, or review production readiness of Python Microsoft 365 Agents SDK agents and their direct hosting\u002Foperations files. Use only for Agents SDK scenarios, not unrelated application hardening.","评估、创建、加固、部署或审查 Python Microsoft 365 Agents SDK 智能体的生产就绪度，以及其直接的托管\u002F运维文件。仅用于 Agents SDK 场景，不用于无关的应用加固。","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002FAgents\u002Fblob\u002Fmain\u002Fagent-plugins\u002Fagents-for-python\u002Fskills\u002Fagents-sdk-to-prod\u002FSKILL.md",[146,147],{"categoryNo":129,"categoryName":130,"taxonomyType":23,"taxonomyTypeDesc":24},{"categoryNo":114,"categoryName":115,"taxonomyType":28,"taxonomyTypeDesc":29},[149,32,31,10,135,150,137],"agents sdk to prod","review",{"skillNo":152,"name":153,"nameZh":154,"description":155,"descriptionZh":156,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":157,"categories":158,"keywords":165,"publishedAt":36},"01M69B8ENJGC9NPQBZAYAN4706","agents-sdk-python-otel","Agents SDK Python 可观测性配置","Use when adding, configuring, validating, or troubleshooting OpenTelemetry observability for a Microsoft 365 Agents SDK application in Python. Trigger when the user mentions OpenTelemetry, OTel, telemetry, traces, metrics, logs, OTLP, Aspire Dashboard, Application Insights, Azure Monitor, distributed tracing, custom tracers or meters, span sampling, or observing microsoft_agents SDK signals.","用于为 Python 版 Microsoft 365 Agents SDK 应用添加、配置、验证或排查 OpenTelemetry 可观测性。当用户提及 OpenTelemetry、OTel、遥测、traces、metrics、logs、OTLP、Aspire Dashboard、Application Insights、Azure Monitor、分布式追踪、自定义 tracer 或 meter、span 采样，或观测 microsoft_agents SDK 信号时触发。","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002FAgents\u002Fblob\u002Fmain\u002Fagent-plugins\u002Fagents-for-python\u002Fskills\u002Fagents-sdk-python-otel\u002FSKILL.md",[159,162],{"categoryNo":160,"categoryName":161,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8BQGD3B3T8FK02S5JVCZA1M","运维监控与告警",{"categoryNo":163,"categoryName":164,"taxonomyType":23,"taxonomyTypeDesc":24},"01M8BQGD4WETX0HM3SM9QKQ15B","SRE 工程师",[31,135,166,32,167,168,118,169,10,170,171,172,173],"otel","agents sdk python otel","aspire","telemetry","dashboard","distributed","aspire dashboard","monitor"]