public async Task <MessagingExtensionActionResponse> Handle(Activity activity)
        {
            var editForm = GetEditForm(activity);

            var localPlannedDrawTime = _dateTimeService.UtcNow.AddHours(2).ToOffset(activity.GetOffset());

            if (!string.IsNullOrEmpty(editForm.PlannedDrawTimeLocalDate) && !string.IsNullOrEmpty(editForm.PlannedDrawTimeLocalTime))
            {
                var dateTime = DateTime.Parse(editForm.PlannedDrawTimeLocalDate + "T" + editForm.PlannedDrawTimeLocalTime, CultureInfo.InvariantCulture);
                localPlannedDrawTime = new DateTimeOffset(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, 0, activity.GetOffset());
            }

            var card     = _activityBuilder.CreateComposeEditForm(editForm.Gift, int.Parse(editForm.WinnerCount), editForm.GiftImageUrl, localPlannedDrawTime, string.Empty, activity.Locale);
            var taskInfo = new TaskModuleContinueResponse
            {
                Type  = "continue",
                Value = new TaskModuleTaskInfo
                {
                    Title = string.Empty,
                    Card  = card
                }
            };

            var response = new MessagingExtensionActionResponse {
                Task = taskInfo
            };

            return(await Task.FromResult(response));
        }
Esempio n. 2
0
        protected override async Task <MessagingExtensionActionResponse> OnTeamsMessagingExtensionFetchTaskAsync(ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction action, CancellationToken cancellationToken)
        {
            //get and store the user details in temp file
            try
            {
                var tempFilePath = @"Temp/UserFile.txt";
                System.IO.File.WriteAllText(tempFilePath, turnContext.Activity.From.Name + "," + turnContext.Activity.From.AadObjectId + "," + turnContext.Activity.From.Id);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            var response = new MessagingExtensionActionResponse()
            {
                Task = new TaskModuleContinueResponse()
                {
                    Value = new TaskModuleTaskInfo()
                    {
                        Height = 400,
                        Width  = 600,
                        //Title = "Invite people to share how they feel",
                        Url = this.configuration["BaseUri"] + "/FileUpload/Upload"
                    },
                },
            };

            return(response);
        }
        // Called when the task module from an action messaging extension  is submitted
        public async Task <MessagingExtensionActionResponse> HandleMessagingExtensionSubmitActionAsync(ITurnContext turnContext, CancellationToken cancellationToken, MessagingExtensionAction action)
        {
            var val        = JObject.FromObject(action.Data); // turnContext.Activity.Value as JObject;
            var payload    = val.ToObject <AddToProjectConfirmationCard.AddToProjectCardActionValue>();
            var submitData = val["msteams"]["value"];

            payload.submissionId = submitData.Value <string>("submissionId");
            payload.command      = submitData.Value <string>("command");
            payload.monthZero    = submitData.Value <string>("monthZero");
            payload.monthOne     = submitData.Value <string>("monthOne");
            payload.monthTwo     = submitData.Value <string>("monthTwo");

            // FROM SAMPLE
            dynamic Data     = JObject.Parse(action.Data.ToString());
            var     response = new MessagingExtensionActionResponse
            {
                ComposeExtension = new MessagingExtensionResult
                {
                    Type            = "botMessagePreview",
                    ActivityPreview = MessageFactory.Attachment(new Attachment
                    {
                        Content     = await AddToProjectConfirmationCard.GetCardAsync(turnContext, payload),
                        ContentType = AdaptiveCard.ContentType
                    }) as Activity
                },
            };

            return(response);
        }
        public void MessagingExtensionActionResponseInitsWithNoArgs()
        {
            var msgExtActionResponse = new MessagingExtensionActionResponse();

            Assert.NotNull(msgExtActionResponse);
            Assert.IsType <MessagingExtensionActionResponse>(msgExtActionResponse);
        }
Esempio n. 5
0
        private MessagingExtensionActionResponse HandleCreateCardCommands(ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction action)
        {
            var actionData     = action.Data;
            var createCardData = ((JObject)actionData).ToObject <CreateCardData>();
            var response       = new MessagingExtensionActionResponse
            {
                ComposeExtension = new MessagingExtensionResult
                {
                    AttachmentLayout = "list",
                    Type             = "result",
                },
            };

            var card = new HeroCard
            {
                Title    = createCardData.Title,
                Subtitle = createCardData.Subtitle,
                Text     = createCardData.Text,
            };

            var attachments = new List <MessagingExtensionAttachment>();

            attachments.Add(new MessagingExtensionAttachment
            {
                Content     = card,
                ContentType = HeroCard.ContentType,
                Preview     = card.ToAttachment(),
            });

            response.ComposeExtension.Attachments = attachments;
            return(response);
        }
Esempio n. 6
0
        protected override async Task <MessagingExtensionActionResponse> OnTeamsMessagingExtensionFetchTaskAsync(ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction action, CancellationToken cancellationToken)
        {
            string memberName;

            try
            {
                // Check if your app is installed by fetching member information.
                var member = await TeamsInfo.GetMemberAsync(turnContext, turnContext.Activity.From.Id, cancellationToken);

                memberName = member.Name;
            }
            catch (ErrorResponseException ex)
            {
                if (ex.Body.Error.Code == "BotNotInConversationRoster")
                {
                    return(new MessagingExtensionActionResponse
                    {
                        Task = new TaskModuleContinueResponse
                        {
                            Value = new TaskModuleTaskInfo
                            {
                                Card = CardHelper.CreateJustInTimeCard("JITinstallation.json"),
                                Height = 200,
                                Width = 400,
                                Title = "Device Capabilities - App Installation",
                            },
                        },
                    });
                }
                throw;
            }

            if (action.CommandId == Constants.MessageExtensionCommandId)
            {
                var response = new MessagingExtensionActionResponse()
                {
                    Task = new TaskModuleContinueResponse()
                    {
                        Value = new TaskModuleTaskInfo()
                        {
                            Height = 450,
                            Width  = 350,
                            Title  = "Bar Code Scanner",
                            Url    = Constants.BaseUrl + "/Scanner",
                        },
                    },
                };
                return(response);
            }
            return(new MessagingExtensionActionResponse());
        }
        /// <inheritdoc/>
        public override async Task <DialogTurnResult> BeginDialogAsync(DialogContext dc, object options = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (options is CancellationToken)
            {
                throw new ArgumentException($"{nameof(options)} cannot be a cancellation token");
            }

            if (Disabled != null && Disabled.GetValue(dc.State))
            {
                return(await dc.EndDialogAsync(cancellationToken : cancellationToken).ConfigureAwait(false));
            }

            Activity activity = null;

            if (Card != null)
            {
                activity = await Card.BindAsync(dc, dc.State).ConfigureAwait(false);
            }

            if (activity?.Attachments?.Any() != true)
            {
                throw new InvalidOperationException($"Missing attachments in {Kind}.");
            }

            var title           = Title.GetValueOrNull(dc.State);
            var height          = Height.GetValueOrNull(dc.State);
            var width           = Width.GetValueOrNull(dc.State);
            var completionBotId = CompletionBotId.GetValueOrNull(dc.State);

            var response = new MessagingExtensionActionResponse
            {
                Task = new TaskModuleContinueResponse
                {
                    Value = new TaskModuleTaskInfo
                    {
                        Card            = activity.Attachments[0],
                        Height          = height,
                        Width           = width,
                        Title           = title,
                        CompletionBotId = completionBotId
                    },
                },
            };

            var invokeResponse   = CreateInvokeResponseActivity(response);
            var resourceResponse = await dc.Context.SendActivityAsync(invokeResponse, cancellationToken).ConfigureAwait(false);

            return(await dc.EndDialogAsync(resourceResponse, cancellationToken : cancellationToken).ConfigureAwait(false));
        }
        public void MessagingExtensionActionResponseInits()
        {
            var task             = new TaskModuleResponseBase("message");
            var composeExtension = new MessagingExtensionResult("list", "message", null, null, "with a personality like sunshine");
            var cacheInfo        = new CacheInfo();

            var msgExtActionResponse = new MessagingExtensionActionResponse(task, composeExtension)
            {
                CacheInfo = cacheInfo
            };

            Assert.NotNull(msgExtActionResponse);
            Assert.IsType <MessagingExtensionActionResponse>(msgExtActionResponse);
            Assert.Equal(task, msgExtActionResponse.Task);
            Assert.Equal(composeExtension, msgExtActionResponse.ComposeExtension);
            Assert.Equal(cacheInfo, msgExtActionResponse.CacheInfo);
        }
Esempio n. 9
0
        private async Task <InvokeResponse> CreateConfirmJobPostingTaskModuleResponse(ITurnContext turnContext, PositionCreateCommand positionCreateCommand, CancellationToken cancellationToken)
        {
            var position = await _positionService.AddNewPosition(positionCreateCommand, cancellationToken);

            positionCreateCommand.CommandId  = AppCommands.ConfirmCreationOfNewPosition;
            positionCreateCommand.PositionId = position.PositionId;

            var positionsTemplate = new PositionTemplateModel
            {
                Items = new List <Position> {
                    position
                },
                ButtonActions = new List <AdaptiveAction>
                {
                    new AdaptiveSubmitAction
                    {
                        Title = "Confirm posting",
                        Data  = positionCreateCommand
                    },
                    new AdaptiveSubmitAction
                    {
                        Title = "Cancel"
                    }
                }
            };

            var messageActivity = await _positionsTemplate.RenderTemplate(turnContext, null, TemplateConstants.PositionAsAdaptiveCardWithMultipleItems, positionsTemplate);

            var actionResponse = new MessagingExtensionActionResponse
            {
                Task = new TaskModuleContinueResponse
                {
                    Type  = "continue",
                    Value = new TaskModuleTaskInfo
                    {
                        Card   = messageActivity.Attachments.First(),
                        Title  = "Confirm new posting",
                        Width  = "medium",
                        Height = "medium"
                    }
                }
            };

            return(_mapper.Map <MessagingExtensionActionResponse, InvokeResponse>(actionResponse));
        }
        /// <inheritdoc/>
        public override async Task <DialogTurnResult> BeginDialogAsync(DialogContext dc, object options = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (options is CancellationToken)
            {
                throw new ArgumentException($"{nameof(options)} cannot be a cancellation token");
            }

            if (Disabled != null && Disabled.GetValue(dc.State))
            {
                return(await dc.EndDialogAsync(cancellationToken : cancellationToken).ConfigureAwait(false));
            }

            if (Card == null)
            {
                throw new ArgumentException($"A valid {nameof(Card)} is required for {Kind}.");
            }

            var activity = await Card.BindAsync(dc, dc.State).ConfigureAwait(false);

            if (activity?.Attachments?.Any() != true)
            {
                throw new InvalidOperationException($"Invalid activity. An attachment is required for {Kind}.");
            }

            Attachment attachment = activity.Attachments[0];

            var response = new MessagingExtensionActionResponse
            {
                ComposeExtension = new MessagingExtensionResult
                {
                    Type            = MEResultResponseType.botMessagePreview.ToString(),
                    ActivityPreview = MessageFactory.Attachment(new Attachment
                    {
                        Content     = attachment.Content,
                        ContentType = attachment.ContentType,
                    }) as Activity,
                },
                CacheInfo = GetCacheInfo(dc),
            };

            var invokeResponse            = CreateInvokeResponseActivity(response);
            ResourceResponse sendResponse = await dc.Context.SendActivityAsync(invokeResponse, cancellationToken : cancellationToken).ConfigureAwait(false);

            return(await dc.EndDialogAsync(sendResponse, cancellationToken : cancellationToken).ConfigureAwait(false));
        }
        private MessagingExtensionActionResponse DateDayInfo(ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction action)
        {
            var response = new MessagingExtensionActionResponse()
            {
                Task = new TaskModuleContinueResponse()
                {
                    Value = new TaskModuleTaskInfo()
                    {
                        Height = 175,
                        Width  = 300,
                        Title  = "Task Module Razor View",
                        Url    = baseUrl + "/Home/RazorView",
                    },
                },
            };

            return(response);
        }
        private MessagingExtensionActionResponse TaskModuleHTMLPage(ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction action)
        {
            var response = new MessagingExtensionActionResponse()
            {
                Task = new TaskModuleContinueResponse()
                {
                    Value = new TaskModuleTaskInfo()
                    {
                        Height = 200,
                        Width  = 400,
                        Title  = "Task Module HTML Page",
                        Url    = baseUrl + "/htmlpage.html",
                    },
                },
            };

            return(response);
        }
        private MessagingExtensionActionResponse EmpDetails(ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction action)
        {
            var response = new MessagingExtensionActionResponse()
            {
                Task = new TaskModuleContinueResponse()
                {
                    Value = new TaskModuleTaskInfo()
                    {
                        Height = 300,
                        Width  = 450,
                        Title  = "Task Module WebView",
                        Url    = baseUrl + "/Home/CustomForm",
                    },
                },
            };

            return(response);
        }
        //protected override async Task<MessagingExtensionActionResponse> OnTeamsMessagingExtensionSubmitActionAsync(ITurnContext<IInvokeActivity> turnContext, MessagingExtensionAction action, CancellationToken cancellationToken)
        //{
        //    var response = new MessagingExtensionActionResponse()
        //    {
        //        Task = new TaskModuleContinueResponse()
        //        {
        //            Value = new TaskModuleTaskInfo()
        //            {
        //                Height = "large",
        //                Width = "large",
        //                Title = "Embed a video",
        //                Url = "https://online.clickview.com.au/share/embed?shareCode=7aac2301&a=false",
        //            },
        //        },
        //    };

        //    return response;


        //}

        protected override async Task <MessagingExtensionActionResponse> OnTeamsMessagingExtensionSubmitActionAsync(ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction action, CancellationToken cancellationToken)
        {
            //dynamic Data = JObject.Parse(action.Data.ToString());
            var response = new MessagingExtensionActionResponse
            {
                ComposeExtension = new MessagingExtensionResult
                {
                    Type            = "botMessagePreview",
                    ActivityPreview = MessageFactory.Attachment(new Attachment
                    {
                        Content = new AdaptiveCard("1.0")
                        {
                            Body = new List <AdaptiveElement>()
                            {
                                new AdaptiveTextBlock()
                                {
                                    Text = "FormField1 value was:", Size = AdaptiveTextSize.Large
                                },
                                new AdaptiveTextBlock()
                                {
                                    Text = "your mother"
                                }
                            },
                            Height  = AdaptiveHeight.Auto,
                            Actions = new List <AdaptiveAction>()
                            {
                                new AdaptiveSubmitAction
                                {
                                    Type  = AdaptiveSubmitAction.TypeName,
                                    Title = "Submit",
                                    Data  = new JObject {
                                        { "submitLocation", "messagingExtensionFetchTask" }
                                    },
                                },
                            }
                        },
                        ContentType = AdaptiveCard.ContentType
                    }) as Activity
                }
            };

            return(response);
        }
Esempio n. 15
0
        public async Task <object> Handle(Activity activity)
        {
            var data                 = ((JObject)activity.Value).GetValue("data");
            var editForm             = JsonSerializer.Deserialize <CompetitionEditForm>(Newtonsoft.Json.JsonConvert.SerializeObject(data));
            var plannedDrawTime      = editForm.GetPlannedDrawTime(activity.GetOffset(), _dateTimeService.UtcNow.AddHours(2));
            var localPlannedDrawTime = plannedDrawTime.ToOffset(activity.GetOffset());

            var errorMessage = CanPreviewCompetition(editForm.Gift, int.Parse(editForm.WinnerCount), plannedDrawTime, editForm.GiftImageUrl, activity.Locale);

            if (string.IsNullOrEmpty(errorMessage))
            {
                var card    = _activityBuilder.CreatePreviewCard(editForm, localPlannedDrawTime, activity.Locale);
                var preview = MessageFactory.Attachment(card) as Activity;
                preview.Value = editForm;
                var response = new MessagingExtensionActionResponse
                {
                    ComposeExtension = new MessagingExtensionResult
                    {
                        Type            = "botMessagePreview",
                        ActivityPreview = preview
                    }
                };
                return(await Task.FromResult(response));
            }
            else
            {
                var card     = _activityBuilder.CreateComposeEditForm(editForm.Gift, int.Parse(editForm.WinnerCount), editForm.GiftImageUrl, localPlannedDrawTime, errorMessage, activity.Locale);
                var taskInfo = new TaskModuleContinueResponse
                {
                    Type  = "continue",
                    Value = new TaskModuleTaskInfo
                    {
                        Title = string.Empty,
                        Width = "medium",
                        Card  = card
                    }
                };
                var response = new MessagingExtensionActionResponse {
                    Task = taskInfo
                };
                return(await Task.FromResult(response));
            }
        }
        protected override async Task <MessagingExtensionActionResponse> OnTeamsMessagingExtensionFetchTaskAsync(ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction action, CancellationToken cancellationToken)
        {
            var TaskDesFromPayload = action.MessagePayload.Body.Content;

            var response = new MessagingExtensionActionResponse()
            {
                Task = new TaskModuleContinueResponse()
                {
                    Value = new TaskModuleTaskInfo()
                    {
                        Height = 620,
                        Width  = 800,
                        //Title = "Invite people to share how they feel",
                        Url = this._configuration["BaseUri"] + "/CreateNewTask/" + TaskDesFromPayload
                    },
                },
            };

            return(response);
        }
Esempio n. 17
0
        protected override async Task <MessagingExtensionActionResponse> OnTeamsMessagingExtensionFetchTaskAsync(ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction action, CancellationToken cancellationToken)
        {
            var response = new MessagingExtensionActionResponse()
            {
                Task = new TaskModuleContinueResponse()
                {
                    Value = new TaskModuleTaskInfo()
                    {
                        Height = 200,
                        Width  = 400,
                        Title  = "Message extension example",
                        Url    = new Uri(
                            new Uri(ConfigurationManager.AppSettings["WebApp.Url"]),
                            "/auth?redirect=/message")
                                 .AbsoluteUri
                    },
                },
            };

            return(response);
        }
Esempio n. 18
0
        public async Task <MessagingExtensionActionResponse> Handle(Activity activity)
        {
            var localPlannedDrawTime = _dateTimeService.UtcNow.AddHours(2).ToOffset(TimeSpan.FromHours(activity.GetOffset().TotalHours));
            var card     = _activityBuilder.CreateComposeEditForm(string.Empty, 1, string.Empty, localPlannedDrawTime, string.Empty, activity.Locale);
            var taskInfo = new TaskModuleContinueResponse
            {
                Type  = "continue",
                Value = new TaskModuleTaskInfo
                {
                    Title = string.Empty,
                    Width = "medium",
                    Card  = card
                }
            };

            var response = new MessagingExtensionActionResponse {
                Task = taskInfo
            };

            return(await Task.FromResult(response));
        }
Esempio n. 19
0
        private MessagingExtensionActionResponse HandleShareMessageCommand(ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction action)
        {
            var heroCard = new HeroCard
            {
                Title = $"{action.MessagePayload.From.User.DisplayName} sent this message:",
                Text  = action.MessagePayload.Body.Content,
            };
            var actionData       = action.Data;
            var includeImageData = ((JObject)actionData).ToObject <IncludeImageData>();

            if (includeImageData.IncludeImage)
            {
                heroCard.Images = new List <CardImage>
                {
                    new CardImage
                    {
                        Url = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQtB3AwMUeNoq4gUBGe6Ocj8kyh3bXa9ZbV7u1fVKQoyKFHdkqU",
                    },
                };
            }

            var response = new MessagingExtensionActionResponse();

            response.ComposeExtension = new MessagingExtensionResult
            {
                Type             = "result",
                AttachmentLayout = "list",
                Attachments      = new List <MessagingExtensionAttachment>
                {
                    new MessagingExtensionAttachment
                    {
                        Content     = heroCard,
                        ContentType = HeroCard.ContentType,
                        Preview     = heroCard.ToAttachment(),
                    },
                },
            };

            return(response);
        }
Esempio n. 20
0
        private async Task <MessagingExtensionActionResponse> Authenticate(ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction query, CancellationToken cancellationToken)
        {
            // Send the login response with the auth link.
            var    botAdapter = (BotFrameworkAdapter)turnContext.Adapter;
            string link       = await botAdapter.GetOauthSignInLinkAsync(turnContext, this.connectionName, cancellationToken);

            var response = new MessagingExtensionActionResponse
            {
                ComposeExtension = new MessagingExtensionResult()
                {
                    Type             = "auth",
                    SuggestedActions = new MessagingExtensionSuggestedAction()
                    {
                        Actions = new List <CardAction>()
                        {
                            new CardAction(type: ActionTypes.OpenUrl, title: Resources.Strings.MessageExtSignInTitle, value: link),
                        },
                    },
                },
            };

            return(response);
        }
Esempio n. 21
0
        public async Task <InvokeResponse> HandleMessagingExtensionFetchTaskAsync(ITurnContext <IInvokeActivity> turnContext, CancellationToken cancellationToken)
        {
            var composeExtensionQuery = turnContext.TurnState.Get <ITeamsContext>().GetMessagingExtensionActionData();
            MessagingExtensionActionResponse response = null;

            if (string.Equals(composeExtensionQuery?.CommandId, MessagingExtensionCommands.OpenNewPosition, StringComparison.OrdinalIgnoreCase))
            {
                var locations = await _locationService.GetAllLocations(cancellationToken);

                var hiringManagers = await _recruiterService.GetAllHiringManagers(cancellationToken);

                var messageActivity = await _newJobPostingToAdaptiveCardTemplate.RenderTemplate(turnContext, null, nameof(NewJobPostingToAdaptiveCardTemplate), new
                {
                    Locations      = locations,
                    HiringManagers = hiringManagers,
                    Description    = string.Empty
                });

                response = new MessagingExtensionActionResponse
                {
                    Task = new TaskModuleContinueResponse
                    {
                        Type  = "continue",
                        Value = new TaskModuleTaskInfo
                        {
                            Card   = messageActivity.Attachments.First(),
                            Title  = "Create new job posting",
                            Width  = "large",
                            Height = "large"
                        }
                    }
                };
            }

            return(_mapper.Map <MessagingExtensionActionResponse, InvokeResponse>(response));
        }
Esempio n. 22
0
        protected override async Task <MessagingExtensionActionResponse> OnTeamsMessagingExtensionFetchTaskAsync(ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction action, CancellationToken cancellationToken)
        {
            if (action.MessagePayload != null)
            {
                var messageText = action.MessagePayload.Body.Content;
                var fromId      = action.MessagePayload.From.User.Id;
            }

            var response = new MessagingExtensionActionResponse()
            {
                Task = new TaskModuleContinueResponse()
                {
                    Value = new TaskModuleTaskInfo()
                    {
                        Height = 720,
                        Width  = 900,
                        Title  = "Invite people to share how they feel",
                        Url    = "https://1f0bd229.ngrok.io/"
                    },
                },
            };

            return(response);
        }
        /// <summary>
        /// Handles messaging extension action of "submit action" asynchronously.
        /// </summary>
        /// <param name="turnContext">The turn context.</param>
        /// <param name="query">The query object of messaging extension action.</param>
        /// <returns>Task tracking operation.</returns>
        public override async Task <InvokeResponse> HandleMessagingExtensionSubmitActionAsync(ITurnContext turnContext, MessagingExtensionAction query)
        {
            bool    done = false;
            JObject data = null;

            if (query.Data != null)
            {
                data = JObject.FromObject(query.Data);
                done = (bool)data["done"];
            }

            var body = new MessagingExtensionActionResponse();

            if (data != null && done)
            {
                string sharedMessage = string.Empty;
                if (query.CommandId.Equals("shareMessage") && query.CommandContext.Equals("message"))
                {
                    sharedMessage = $"Shared message: <div style=\"background:#F0F0F0\">{JObject.FromObject(query.MessagePayload).ToString()}</div><br/>";
                }

                var preview     = new ThumbnailCard("Created Card", null, $"Your input: {data["userText"]?.ToString()}").ToAttachment();
                var heroCard    = new HeroCard("Created Card", null, $"{sharedMessage}Your input: {data["userText"]?.ToString()}").ToAttachment();
                var resultCards = new List <MessagingExtensionAttachment> {
                    heroCard.ToMessagingExtensionAttachment(preview)
                };

                body.ComposeExtension = new MessagingExtensionResult("list", "result", resultCards);
            }
            else if ((query.CommandId != null && query.CommandId.Equals("createWithPreview")) || query.BotMessagePreviewAction != null)
            {
                if (query.BotMessagePreviewAction == null)
                {
                    body.ComposeExtension = new MessagingExtensionResult
                    {
                        Type            = "botMessagePreview",
                        ActivityPreview = new Activity
                        {
                            Attachments = new List <Attachment> {
                                this.TaskModuleResponseCard(query, null)
                            },
                        },
                    };
                }
                else
                {
                    var userEditActivities = query.BotActivityPreview;
                    var card = userEditActivities?[0]?.Attachments?[0];
                    if (card == null)
                    {
                        body.Task = new TaskModuleMessageResponse
                        {
                            Type  = "message",
                            Value = "Missing user edit card. Something wrong on Teams client.",
                        };
                    }
                    else if (query.BotMessagePreviewAction.Equals("send"))
                    {
                        Activity activity = turnContext.Activity.CreateReply();
                        activity.Attachments = new List <Attachment> {
                            card
                        };
                        await turnContext.SendActivityAsync(activity).ConfigureAwait(false);
                    }
                    else if (query.BotMessagePreviewAction.Equals("edit"))
                    {
                        body.Task = new TaskModuleContinueResponse
                        {
                            Type  = "continue",
                            Value = new TaskModuleTaskInfo
                            {
                                Card = card,
                            },
                        };
                    }
                }
            }
            else
            {
                body.Task = this.TaskModuleResponseTask(query, false);
            }

            return(new InvokeResponse
            {
                Status = 200,
                Body = body,
            });
        }
        /// <summary>
        /// On Teams Messaging Extension Submit Action Async.
        /// </summary>
        /// <param name="turnContext">turnContext.</param>
        /// <param name="action">action.</param>
        /// <param name="cancellationToken">cancellationToken.</param>
        /// <returns>.</returns>
        protected override async Task <MessagingExtensionActionResponse> OnTeamsMessagingExtensionSubmitActionAsync(ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction action, CancellationToken cancellationToken)
        {
            _telemetry.TrackEvent("OnTeamsMessagingExtensionSubmitActionAsync");
            ReflectionDataRepository reflectionDataRepository = new ReflectionDataRepository(_configuration, _telemetry);

            try
            {
                TaskInfo taskInfo = JsonConvert.DeserializeObject <TaskInfo>(action.Data.ToString());
                switch (taskInfo.action)
                {
                case "reflection":
                    return(await OnTeamsMessagingExtensionFetchTaskAsync(turnContext, action, cancellationToken));

                case "sendAdaptiveCard":
                    try
                    {
                        var name = (turnContext.Activity.From.Name).Split();
                        taskInfo.postCreateBy       = name[0] + ' ' + name[1];
                        taskInfo.postCreatedByEmail = await _dbHelper.GetUserEmailId(turnContext);

                        taskInfo.channelID        = turnContext.Activity.TeamsGetChannelId();
                        taskInfo.postSendNowFlag  = (taskInfo.executionTime == "Send now") ? true : false;
                        taskInfo.IsActive         = true;
                        taskInfo.questionRowKey   = Guid.NewGuid().ToString();
                        taskInfo.recurrsionRowKey = Guid.NewGuid().ToString();
                        taskInfo.reflectionRowKey = Guid.NewGuid().ToString();
                        taskInfo.serviceUrl       = turnContext.Activity.ServiceUrl;
                        taskInfo.teantId          = turnContext.Activity.Conversation.TenantId;
                        taskInfo.scheduleId       = Guid.NewGuid().ToString();
                        await _dbHelper.SaveReflectionDataAsync(taskInfo);

                        if (taskInfo.postSendNowFlag == true)
                        {
                            var typingActivity = MessageFactory.Text(string.Empty);
                            typingActivity.Type = ActivityTypes.Typing;
                            await turnContext.SendActivityAsync(typingActivity);

                            var adaptiveCard = _cardHelper.CreateNewReflect(taskInfo);
                            var message      = MessageFactory.Attachment(new Attachment {
                                ContentType = AdaptiveCard.ContentType, Content = adaptiveCard
                            });
                            var resultid = await turnContext.SendActivityAsync(message, cancellationToken);

                            ReflectionDataEntity reflectData = await reflectionDataRepository.GetReflectionData(taskInfo.reflectionID);

                            reflectData.ReflectMessageId = resultid.Id;
                            await reflectionDataRepository.InsertOrMergeAsync(reflectData);

                            try
                            {
                                var feedbackCard = _cardHelper.FeedBackCard(new Dictionary <int, List <FeedbackDataEntity> >(), taskInfo.reflectionID, taskInfo.question);

                                Attachment attachmentfeedback = new Attachment()
                                {
                                    ContentType = AdaptiveCard.ContentType,
                                    Content     = feedbackCard,
                                };
                                using var connector = new ConnectorClient(new Uri(reflectData.ServiceUrl), _configuration["MicrosoftAppId"], _configuration["MicrosoftAppPassword"]);

                                var conversationId = $"{reflectData.ChannelID};messageid={reflectData.ReflectMessageId}";
                                var replyActivity  = MessageFactory.Attachment(new Attachment {
                                    ContentType = AdaptiveCard.ContentType, Content = feedbackCard
                                });
                                replyActivity.Conversation = new ConversationAccount(id: conversationId);
                                var resultfeedback = await connector.Conversations.SendToConversationAsync((Activity)replyActivity, cancellationToken);

                                reflectData.MessageID = resultfeedback.Id;
                                // update messageid in reflection table
                                await reflectionDataRepository.InsertOrMergeAsync(reflectData);
                            }
                            catch (System.Exception e)
                            {
                                _telemetry.TrackException(e);
                                Console.WriteLine(e.Message.ToString());
                            }
                        }
                        return(null);
                    }
                    catch (Exception ex)
                    {
                        _telemetry.TrackException(ex);
                        return(null);
                    }

                case "ManageRecurringPosts":
                    var postCreatedByEmail = await _dbHelper.GetUserEmailId(turnContext);

                    var response = new MessagingExtensionActionResponse()
                    {
                        Task = new TaskModuleContinueResponse()
                        {
                            Value = new TaskModuleTaskInfo()
                            {
                                Height = 600,
                                Width  = 780,
                                Title  = "Track how you're feeling every day.",
                                Url    = this._configuration["BaseUri"] + "/ManageRecurringPosts/" + postCreatedByEmail + "?pathfromindex=true"
                            },
                        },
                    };
                    return(response);

                case "OpenDetailfeedback":
                    var responsefeedback = new MessagingExtensionActionResponse()
                    {
                        Task = new TaskModuleContinueResponse()
                        {
                            Value = new TaskModuleTaskInfo()
                            {
                                Height = 600,
                                Width  = 780,
                                Title  = "Track how you're feeling every day.",
                                Url    = this._configuration["BaseUri"] + "/openReflectionFeedback/" + taskInfo.reflectionID + "/" + taskInfo.feedback,
                            },
                        },
                    };
                    return(responsefeedback);

                case "removeposts":
                    try
                    {
                        var activity = Activity.CreateMessageActivity();
                        if (taskInfo.isDelete)
                        {
                            var messageId = await _dbHelper.RemoveReflectionId(taskInfo.messageID);

                            if (messageId != null)
                            {
                                await turnContext.DeleteActivityAsync(messageId);
                            }
                            await turnContext.DeleteActivityAsync(taskInfo.messageID);

                            activity.Text = "This post has been removed";
                            await turnContext.SendActivityAsync(activity);

                            return(null);
                        }
                        else
                        {
                            return(null);
                        }
                    }
                    catch (Exception ex)
                    {
                        _telemetry.TrackException(ex);
                        return(null);
                    }

                default:
                    return(null);
                }
                ;
            }
            catch (Exception ex)
            {
                _telemetry.TrackException(ex);
                return(null);
            }
        }
        /// <summary>
        /// On Teams Messaging Extension Fetch Task Async.
        /// </summary>
        /// <param name="turnContext">turnContext.</param>
        /// <param name="action">action.</param>
        /// <param name="cancellationToken">cancellationToken.</param>
        /// <returns>response.</returns>
        protected override async Task <MessagingExtensionActionResponse> OnTeamsMessagingExtensionFetchTaskAsync(ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction action, CancellationToken cancellationToken)
        {
            _telemetry.TrackEvent("OnTeamsMessagingExtensionFetchTaskAsync");

            try
            {
                var url = this._configuration["BaseUri"];
                if (action.CommandId == ReflectConstants.RecurringPosts)
                {
                    var postCreatedByEmail = await _dbHelper.GetUserEmailId(turnContext);

                    url = this._configuration["BaseUri"] + "/ManageRecurringPosts/" + postCreatedByEmail;
                    var response = new MessagingExtensionActionResponse()
                    {
                        Task = new TaskModuleContinueResponse()
                        {
                            Value = new TaskModuleTaskInfo()
                            {
                                Height = 620,
                                Width  = 800,
                                Title  = "Track how you're feeling every day.",
                                Url    = url
                            },
                        },
                    };
                    return(response);
                }
                else if (action.CommandId == ReflectConstants.RemovePosts)
                {
                    if (turnContext.Activity.Conversation.Id != null)
                    {
                        var    replymessageid = turnContext.Activity.Conversation.Id.Split("=");
                        string messageId      = replymessageid[1];
                        var    confirmcard    = _cardHelper.ConfirmationCard(messageId);

                        Attachment attachmentfeedback = new Attachment()
                        {
                            ContentType = AdaptiveCard.ContentType,
                            Content     = confirmcard,
                        };
                        var response = new MessagingExtensionActionResponse()
                        {
                            Task = new TaskModuleContinueResponse()
                            {
                                Value = new TaskModuleTaskInfo()
                                {
                                    Height = 100,
                                    Width  = 300,
                                    Title  = "Track how you're feeling every day.",
                                    Card   = attachmentfeedback
                                },
                            },
                        };
                        return(response);
                    }

                    return(null);
                }
                else if (action.CommandId == ReflectConstants.CreateReflect)
                {
                    var name     = (turnContext.Activity.From.Name).Split();
                    var userName = name[0] + ' ' + name[1];
                    url = this._configuration["BaseUri"] + "/" + userName;
                    var response = new MessagingExtensionActionResponse()
                    {
                        Task = new TaskModuleContinueResponse()
                        {
                            Value = new TaskModuleTaskInfo()
                            {
                                Height = 620,
                                Width  = 800,
                                Title  = "Track how you're feeling every day.",
                                Url    = url
                            },
                        },
                    };
                    return(response);
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception ex)
            {
                _telemetry.TrackException(ex);
                return(null);
            }
        }