private async Task <HttpResponseMessage> RejectMessageFromUnexpectedTenant(Activity activity, ConnectorClient connectorClient)
        {
            //Set the OFFICE_365_TENANT_FILTER key in web.config file with Tenant Information
            //Validate bot for specific teams tenant if any
            string currentTenant = "#ANY#";

            try
            {
                currentTenant = activity.GetTenantId();
            }
            catch (Exception e)
            {
                Trace.TraceError($"Exception from activity.GetTenantId(): {e}");
            }

            if (Middleware.RejectMessageBasedOnTenant(activity, currentTenant))
            {
                Bot.Connector.Activity replyActivity = activity.CreateReply();
                replyActivity.Text = Strings.TenantLevelDeniedAccess;

                await BotConnectorUtility.BuildRetryPolicy().ExecuteAsync(async() =>
                                                                          await connectorClient.Conversations.ReplyToActivityAsync(replyActivity));

                {
                    return(Request.CreateResponse(HttpStatusCode.OK));
                }
            }

            return(null);
        }
        /// <summary>
        /// POST: api/Messages
        /// Receive a message from a user and reply to it
        /// </summary>
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity, CancellationToken cancellationToken)
        {
            var connectorClient = await BotConnectorUtility.BuildConnectorClientAsync(activity.ServiceUrl);

            try
            {
                if (activity.Type == ActivityTypes.Message)
                {
                    // Special handling for a command to simulate a reset of the bot chat
                    if (!(activity.Conversation.IsGroup ?? false) && (activity.Text == "/resetbotchat"))
                    {
                        return(await HandleResetBotChatAsync(activity, cancellationToken));
                    }

                    //Set the Locale for Bot
                    activity.Locale = TemplateUtility.GetLocale(activity);

                    //Strip At mention from incoming request text
                    activity = Middleware.StripAtMentionText(activity);

                    //Convert incoming activity text to lower case, to match the intent irrespective of incoming text case
                    activity = Middleware.ConvertActivityTextToLower(activity);

                    // todo: enable tenant check
                    //var unexpectedTenantResponse = await RejectMessageFromUnexpectedTenant(activity, connectorClient);
                    //if (unexpectedTenantResponse != null) return unexpectedTenantResponse;

                    //await Conversation.SendAsync(activity, () => ActivityHelper.IsConversationPersonal(activity)
                    //    ? (IDialog<object>)new UserRootDialog()
                    //    : new AgentRootDialog());

                    await Conversation.SendAsync(activity, () => ActivityHelper.GetRootDialog(activity));

                    //await Conversation.SendAsync(activity, () => ActivityHelper.IsConversationPersonal(activity)
                    //    ? new ExceptionHandlerDialog<object>(new UserRootDialog(),
                    //        displayException: true)
                    //    : new ExceptionHandlerDialog<object>(new AgentRootDialog(),
                    //        displayException: true));
                }
                else if (activity.Type == ActivityTypes.MessageReaction)
                {
                    var reactionsAdded   = activity.ReactionsAdded;
                    var reactionsRemoved = activity.ReactionsRemoved;
                    var replytoId        = activity.ReplyToId;
                    Bot.Connector.Activity reply;

                    if (reactionsAdded != null && reactionsAdded.Count > 0)
                    {
                        reply = activity.CreateReply(Strings.LikeMessage);
                        await BotConnectorUtility.BuildRetryPolicy().ExecuteAsync(async() =>
                                                                                  await connectorClient.Conversations.ReplyToActivityAsync(reply));
                    }
                    else if (reactionsRemoved != null && reactionsRemoved.Count > 0)
                    {
                        reply = activity.CreateReply(Strings.RemoveLike);
                        await BotConnectorUtility.BuildRetryPolicy().ExecuteAsync(async() =>
                                                                                  await connectorClient.Conversations.ReplyToActivityAsync(reply));
                    }

                    return(Request.CreateResponse(HttpStatusCode.OK));
                }
                else if (activity.Type == ActivityTypes.Invoke) // Received an invoke
                {
                    // Handle ComposeExtension query
                    if (activity.IsComposeExtensionQuery())
                    {
                        WikipediaComposeExtension wikipediaComposeExtension = new WikipediaComposeExtension();
                        HttpResponseMessage       httpResponse = null;

                        using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, activity))
                        {
                            var botDataStore = scope.Resolve <IBotDataStore <BotData> >();
                            // Handle compose extension selected item
                            if (activity.Name == "composeExtension/selectItem")
                            {
                                // This handler is used to process the event when a user in Teams selects wiki item from wiki result
                                ComposeExtensionResponse selectedItemResponse = await wikipediaComposeExtension.HandleComposeExtensionSelectedItem(activity, botDataStore);

                                httpResponse = Request.CreateResponse <ComposeExtensionResponse>(HttpStatusCode.OK, selectedItemResponse);
                            }
                            else
                            {
                                // Handle the wiki compose extension request and returned the wiki result response
                                ComposeExtensionResponse composeExtensionResponse = await wikipediaComposeExtension.GetComposeExtensionResponse(activity, botDataStore);

                                httpResponse = Request.CreateResponse <ComposeExtensionResponse>(HttpStatusCode.OK, composeExtensionResponse);
                            }

                            var address = Address.FromActivity(activity);
                            await botDataStore.FlushAsync(address, CancellationToken.None);
                        }
                        return(httpResponse);
                    }
                    //Actionable Message
                    else if (activity.IsO365ConnectorCardActionQuery())
                    {
                        // this will handle the request coming any action on Actionable messages
                        return(await HandleO365ConnectorCardActionQuery(activity));
                    }
                    //PopUp SignIn
                    else if (activity.Name == "signin/verifyState")
                    {
                        // this will handle the request coming from PopUp SignIn
                        return(await PopUpSignInHandler(activity));
                    }
                    // Handle rest of the invoke request
                    else
                    {
                        var messageActivity = (IMessageActivity)null;

                        //this will parse the invoke value and change the message activity as well
                        messageActivity = InvokeHandler.HandleInvokeRequest(activity);

                        await Conversation.SendAsync(activity, () => ActivityHelper.GetRootDialog(activity));

                        //await Conversation.SendAsync(activity, () => ActivityHelper.IsConversationPersonal(activity)
                        //    ? (IDialog<object>) new UserRootDialog()
                        //    : new AgentRootDialog());

                        //await Conversation.SendAsync(messageActivity, () => ActivityHelper.IsConversationPersonal(messageActivity)
                        //    ? new ExceptionHandlerDialog<object>(new UserRootDialog(),
                        //        displayException: true)
                        //    : new ExceptionHandlerDialog<object>(new AgentRootDialog(),
                        //        displayException: true));

                        return(Request.CreateResponse(HttpStatusCode.OK));
                    }
                }
                else
                {
                    await HandleSystemMessageAsync(activity, connectorClient, cancellationToken);
                }
            }
            catch (Exception e)
            {
                WebApiConfig.TelemetryClient.TrackException(e, new Dictionary <string, string>
                {
                    { "class", "MessagesController" }
                });
                throw;
            }

            var response = Request.CreateResponse(HttpStatusCode.OK);

            return(response);
        }
        public static async Task <ConversationResourceResponse> CreateAgentConversation(ChannelInfo targetChannelInfo,
                                                                                        AdaptiveCard card,
                                                                                        string topicName,
                                                                                        ConnectorClient connector,
                                                                                        int vsoTicketNumber,
                                                                                        IMessageActivity endUserActivity)
        {
            try
            {
                var channelData = new TeamsChannelData {
                    Channel = targetChannelInfo
                };

                IMessageActivity agentMessage = Activity.CreateMessageActivity();
                agentMessage.From       = endUserActivity.Recipient;
                agentMessage.Recipient  = new ChannelAccount(ConfigurationManager.AppSettings["AgentToAssignVsoTasksTo"]);
                agentMessage.Type       = ActivityTypes.Message;
                agentMessage.ChannelId  = ActivityHelper.MsTeamChannelId;
                agentMessage.ServiceUrl = endUserActivity.ServiceUrl;

                agentMessage.Attachments = new List <Attachment>
                {
                    new Attachment {
                        ContentType = AdaptiveCard.ContentType, Content = card
                    }
                };

                var agentMessageActivity = (Activity)agentMessage;

                ConversationParameters conversationParams = new ConversationParameters(
                    isGroup: true,
                    bot: null,
                    members: null,
                    topicName: topicName,
                    activity: agentMessageActivity,
                    channelData: channelData);

                var conversationResourceResponse = await BotConnectorUtility.BuildRetryPolicy().ExecuteAsync(async()
                                                                                                             => await connector.Conversations.CreateConversationAsync(conversationParams));

                Trace.TraceInformation($"[SUCCESS]: CreateAgentConversation. " +
                                       $"response id ={conversationResourceResponse.Id} vsoId={vsoTicketNumber} ");

                WebApiConfig.TelemetryClient.TrackEvent("CreateAgentConversation", new Dictionary <string, string>
                {
                    { "endUser", agentMessage.From.Name },
                    { "agentConversationId", conversationResourceResponse.Id },
                    { "vsoId", vsoTicketNumber.ToString() },
                });

                return(conversationResourceResponse);
            }
            catch (System.Exception e)
            {
                WebApiConfig.TelemetryClient.TrackException(e, new Dictionary <string, string>
                {
                    { "function", "CreateAgentConversation" },
                    { "endUser", endUserActivity.Recipient.Name },
                    { "vsoId", vsoTicketNumber.ToString() }
                });

                throw;
            }
        }
        public static async Task <string> CreateAgentConversationEx(IDialogContext context,
                                                                    string topicName,
                                                                    AdaptiveCard cardToSend,
                                                                    UserProfile endUserProfile)
        {
            string serviceUrl = GetServiceUrl(context);

            var agentChannelInfo = await IdTable.GetAgentChannelInfo();

            ChannelAccount botMsTeamsChannelAccount = context.Activity.ChannelId == ActivityHelper.SmsChannelId
                ? await IdTable.GetBotId()
                : context.Activity.From;

            using (var connectorClient = await BotConnectorUtility.BuildConnectorClientAsync(serviceUrl))
            {
                try
                {
                    var channelData = new TeamsChannelData {
                        Channel = agentChannelInfo
                    };

                    IMessageActivity agentMessage = Activity.CreateMessageActivity();
                    agentMessage.From      = botMsTeamsChannelAccount;
                    agentMessage.Recipient =
                        new ChannelAccount(ConfigurationManager.AppSettings["AgentToAssignVsoTasksTo"]);
                    agentMessage.Type       = ActivityTypes.Message;
                    agentMessage.ChannelId  = ActivityHelper.MsTeamChannelId;
                    agentMessage.ServiceUrl = serviceUrl;

                    agentMessage.Attachments = new List <Attachment>
                    {
                        new Attachment {
                            ContentType = AdaptiveCard.ContentType, Content = cardToSend
                        }
                    };

                    var agentMessageActivity = (Activity)agentMessage;

                    ConversationParameters conversationParams = new ConversationParameters(
                        isGroup: true,
                        bot: null,
                        members: null,
                        topicName: topicName,
                        activity: agentMessageActivity,
                        channelData: channelData);

                    var conversationResourceResponse = await BotConnectorUtility.BuildRetryPolicy().ExecuteAsync(
                        async()
                        => await connectorClient.Conversations.CreateConversationAsync(conversationParams));

                    Trace.TraceInformation(
                        $"[SUCCESS]: CreateAgentConversation. response id ={conversationResourceResponse.Id}");

                    WebApiConfig.TelemetryClient.TrackEvent("CreateAgentConversation", new Dictionary <string, string>
                    {
                        { "endUser", agentMessage.From.Name },
                        { "agentConversationId", conversationResourceResponse.Id },
                    });

                    return(conversationResourceResponse.Id);
                }
                catch (System.Exception e)
                {
                    WebApiConfig.TelemetryClient.TrackException(e, new Dictionary <string, string>
                    {
                        { "function", "CreateAgentConversation" }
                    });

                    throw;
                }
            }
        }