Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Build Feature Bot-Tab-Interoperability Csharp Sample #1277

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions samples/bot-tab-interoperability/csharp/AdapterWithErrorHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// <copyright file="AdapterWithErrorHandler.cs" company="Microsoft Corporation">
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
// </copyright>

using Microsoft.Bot.Builder.Integration.AspNet.Core;
using Microsoft.Bot.Builder.TraceExtensions;
using Microsoft.Bot.Connector.Authentication;
using Microsoft.Extensions.Logging;

namespace Microsoft.BotBuilderSamples
{
public class AdapterWithErrorHandler : CloudAdapter
{
public AdapterWithErrorHandler(BotFrameworkAuthentication auth, ILogger<IBotFrameworkHttpAdapter> logger)
: base(auth, logger)
{
OnTurnError = async (turnContext, exception) =>
{
// Log any leaked exception from the application.
// NOTE: In production environment, you should consider logging this to
// Azure Application Insights. Visit https://aka.ms/bottelemetry to see how
// to add telemetry capture to your bot.
logger.LogError($"Exception caught : {exception.Message}");

// Uncomment below commented line for local debugging.
// await turnContext.SendActivityAsync($"Sorry, it looks like something went wrong. Exception Caught: {exception.Message}");

// Send a trace activity, which will be displayed in the Bot Framework Emulator
await turnContext.TraceActivityAsync("OnTurnError Trace", exception.Message, "https://www.botframework.com/schemas/error", "TurnError");
};
}
}
}
62 changes: 62 additions & 0 deletions samples/bot-tab-interoperability/csharp/AnonymousUsers.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<SpaRoot>ClientApp\</SpaRoot>
<DefaultItemExcludes>$(DefaultItemExcludes);$(SpaRoot)node_modules\**</DefaultItemExcludes>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="AdaptiveCards" Version="3.0.0" />
<PackageReference Include="AdaptiveCards.Templating" Version="1.3.2" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="6.0.11" />
<PackageReference Include="Microsoft.AspNetCore.WebSockets" Version="2.2.1" />
<PackageReference Include="Microsoft.Bot.Builder.Integration.ApplicationInsights.Core" Version="4.19.1" />
<PackageReference Include="Microsoft.Bot.Builder.Integration.AspNet.Core" Version="4.22.3" />
<PackageReference Include="Microsoft.AspNetCore.SpaServices" Version="3.1.31" />
<PackageReference Include="Microsoft.AspNetCore.SpaServices.Extensions" Version="6.0.11" />
<PackageReference Include="Microsoft.Graph" Version="4.46.0" />

</ItemGroup>

<ItemGroup>
<!-- Don't publish the SPA source files, but do show them in the project files list -->
<Compile Remove="demo-manifest\**" />
<Content Remove="$(SpaRoot)**" />
<Content Remove="demo-manifest\**" />
<EmbeddedResource Remove="demo-manifest\**" />
<None Remove="$(SpaRoot)**" />
<None Remove="demo-manifest\**" />
<None Include="$(SpaRoot)**" Exclude="$(SpaRoot)node_modules\**" />
</ItemGroup>

<ItemGroup>
<None Include="AnonymousUsers.sln" />
</ItemGroup>

<Target Name="DebugEnsureNodeEnv" BeforeTargets="Build" Condition=" '$(Configuration)' == 'Debug' And !Exists('$(SpaRoot)node_modules') ">
<!-- Ensure Node.js is installed -->
<Exec Command="node --version" ContinueOnError="true">
<Output TaskParameter="ExitCode" PropertyName="ErrorCode" />
</Exec>
<Error Condition="'$(ErrorCode)' != '0'" Text="Node.js is required to build and run this project. To continue, please install Node.js from https://nodejs.org/, and then restart your command prompt or IDE." />
<Message Importance="high" Text="Restoring dependencies using 'npm'. This may take several minutes..." />
<Exec WorkingDirectory="$(SpaRoot)" Command="npm install" />
</Target>

<Target Name="PublishRunWebpack" AfterTargets="ComputeFilesToPublish">
<!-- As part of publishing, ensure the JS resources are freshly built in production mode -->
<Exec WorkingDirectory="$(SpaRoot)" Command="npm install" />
<Exec WorkingDirectory="$(SpaRoot)" Command="npm run build" />

<!-- Include the newly-built files in the publish output -->
<ItemGroup>
<DistFiles Include="$(SpaRoot)build\**" />
<ResolvedFileToPublish Include="@(DistFiles->'%(FullPath)')" Exclude="@(ResolvedFileToPublish)">
<RelativePath>%(DistFiles.Identity)</RelativePath>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
</ResolvedFileToPublish>
</ItemGroup>
</Target>
</Project>
25 changes: 25 additions & 0 deletions samples/bot-tab-interoperability/csharp/AnonymousUsers.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.3.32901.215
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AnonymousUsers", "AnonymousUsers.csproj", "{76D60C04-94EB-4042-B141-C2C0FACBDE94}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{76D60C04-94EB-4042-B141-C2C0FACBDE94}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{76D60C04-94EB-4042-B141-C2C0FACBDE94}.Debug|Any CPU.Build.0 = Debug|Any CPU
{76D60C04-94EB-4042-B141-C2C0FACBDE94}.Release|Any CPU.ActiveCfg = Release|Any CPU
{76D60C04-94EB-4042-B141-C2C0FACBDE94}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {29EE0BD1-BA0E-4D58-9F98-023E02D8B72E}
EndGlobalSection
EndGlobal
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
59 changes: 59 additions & 0 deletions samples/bot-tab-interoperability/csharp/AppManifest/manifest.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/teams/v1.16/MicrosoftTeams.schema.json",
"manifestVersion": "1.16",
"version": "1.0.0",
"id": "",
"packageName": "com.teams.sample.appAnonymousUsers",
"developer": {
"name": "appAnonymousUsers",
"websiteUrl": "https://www.microsoft.com",
"privacyUrl": "https://www.teams.com/privacy",
"termsOfUseUrl": "https://www.teams.com/termsofuser"
},
"icons": {
"outline": "outline.png",
"color": "color.png"
},
"name": {
"short": "Anonymous User Support",
"full": "Anonymous User Support"
},
"description": {
"short": "This sample shows anonymous users support in Teams meeting apps.",
"full": "This sample shows anonymous users support in Teams meeting apps."
},
"accentColor": "#FFFFFF",
"staticTabs": [
{
"entityId": "tab1",
"name": "Color Tab",
"contentUrl": "https:///appmeeting",
"scopes": [
"personal"
]
}
],
"bots": [
{
"botId": "",
"scopes": [
"personal"
],
"isNotificationOnly": false,
"supportsCalling": false,
"supportsVideo": false,
"supportsFiles": false
}
],
"permissions": [
"identity",
"messageTeamMembers"
],
"validDomains": [
""
],
"webApplicationInfo": {
"id": "",
"resource": ""
}
}
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
111 changes: 111 additions & 0 deletions samples/bot-tab-interoperability/csharp/Bots/AnonymousUsersBot.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
// <copyright file="AnonymousUsersBot.cs" company="Microsoft Corporation">
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
// </copyright>

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.Teams;
using Microsoft.Bot.Schema;
using Microsoft.Bot.Schema.Teams;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace AnonymousUsers.Bots
{
public class AnonymousUsersBot : TeamsActivityHandler
{

/// <summary>
/// Get the Microsoft appid and assign the value to the _appId properties.
/// </summary>
private string _appId;

/// <summary>
/// Get the Microsoft password and assign the value to the _appPassword properties.
/// </summary>
private string _appPassword;

/// <summary>
/// Assgin_logger error data and the _logger field shouldn't be modified.
/// </summary>
private readonly ILogger _logger;


/// <summary>
/// Represents a set of key/value application configuration properties.
/// </summary>
/// <param name="config"></param>
public AnonymousUsersBot(IConfiguration config, ILogger<AnonymousUsersBot> logger)
{
_logger = logger;
_appId = config["MicrosoftAppId"];
_appPassword = config["MicrosoftAppPassword"];
}

/// <summary>
/// Handle when a message is addressed to the bot.
/// </summary>
/// <param name="turnContext">Context object containing information cached for a single turn of conversation with a user.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns>A task that represents the work queued to execute.</returns>
protected override async Task OnMessageActivityAsync(ITurnContext<IMessageActivity> turnContext, CancellationToken cancellationToken)
{
if (turnContext.Activity.Text != null)
{
var text = turnContext.Activity.Text.Trim().ToLower();
await turnContext.SendActivityAsync(text);
}

}

/// <summary>
/// Invoked when bot (like a user) are added to the conversation.
/// </summary>
/// <param name="membersAdded">A list of all the members added to the conversation.</param>
/// <param name="teamInfo">The team info object representing the team.</param>
/// <param name="turnContext">Context object containing information cached for a single turn of conversation with a user.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns>A task that represents the work queued to execute.</returns>
/// <remarks>
protected override async Task OnTeamsMembersAddedAsync(IList<TeamsChannelAccount> membersAdded, TeamInfo teamInfo, ITurnContext<IConversationUpdateActivity> turnContext, CancellationToken cancellationToken)
{
foreach (var teamMember in membersAdded)
{
await turnContext.SendActivityAsync(MessageFactory.Text($"Welcome to the team {teamMember.GivenName} {teamMember.Surname}."), cancellationToken);
}
var threadId = GetTeamsThreadId(turnContext);

//await turnContext.SendActivityAsync(MessageFactory.Text(threadId));
}

private string GetTeamsThreadId(ITurnContext<IConversationUpdateActivity> turnContext)
{
// If not in a personal scope, the threadId will be included in the activity
if (turnContext.Activity.Conversation.ConversationType != "personal")
{
return turnContext.Activity.Conversation.Id;
}

// Verify that the user has a valid aadObjectId
var userAadId = turnContext.Activity.From.AadObjectId;
if (string.IsNullOrEmpty(userAadId))
{
throw new Exception("Invalid AAD id for user");
}

// When in a personal scope, we need to construct the threadId manually
// This assumes your bot AAD clientId is named BOT_ID in your environment variables
var botId = "9b8d4c4a-6e5f-404b-90ce-4cb590142a13";
if (string.IsNullOrEmpty(botId))
{
throw new Exception("BOT_ID environment variable not set");
}

return $"19:{userAadId}_{botId}@unq.gbl.spaces";
}
}
}
3 changes: 3 additions & 0 deletions samples/bot-tab-interoperability/csharp/ClientApp/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
REACT_APP_MICROSOFT_APP_ID=""
REACT_APP_MICROSOFT_PASSWORD=""

23 changes: 23 additions & 0 deletions samples/bot-tab-interoperability/csharp/ClientApp/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js

# testing
/coverage

# production
/build

# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local

npm-debug.log*
yarn-debug.log*
yarn-error.log*
Loading