protected override Task <TaskModuleResponse> OnTeamsTaskModuleFetchAsync(ITurnContext <IInvokeActivity> turnContext, TaskModuleRequest taskModuleRequest, CancellationToken cancellationToken) { var asJobject = JObject.FromObject(taskModuleRequest.Data); var formname = asJobject["data"].ToString(); TaskModuleResponse taskModuleResponse = null; switch (formname) { case "alertform": { var taskInfo = new TaskModuleTaskInfo(); taskInfo.Url = taskUrl; taskInfo.Width = 510; taskInfo.Height = 500; taskInfo.Title = "Fetched from bot"; taskModuleResponse = new TaskModuleResponse { Task = new TaskModuleContinueResponse() { Value = taskInfo, }, }; } break; default: break; } return(Task.FromResult(taskModuleResponse)); }
protected override async Task <TaskModuleResponse> OnTeamsTaskModuleFetchAsync( ITurnContext <IInvokeActivity> turnContext, TaskModuleRequest taskModuleRequest, CancellationToken cancellationToken) { var token = ((JObject)taskModuleRequest.Data)["data"].Value <string>(); var url = $"https://{ _configuration["CodeConversationsDomain"]}/executor?Token={token}"; return(new TaskModuleResponse { Task = new TaskModuleContinueResponse { Type = "continue", Value = new TaskModuleTaskInfo { Height = "large", Width = "large", Title = "Powered by .NET interactive aka.ms/codeconversations", Url = url, FallbackUrl = url } } }); }
private TaskModuleResponseBase TaskModuleResponseTask(TaskModuleRequest query, bool done) { if (done) { return(new TaskModuleMessageResponse() { Type = "message", Value = "Thanks for your inputs!", }); } else { string textValue = null; if (query.Data != null) { var data = JObject.FromObject(query.Data); textValue = data["userText"]?.ToString(); } return(new TaskModuleContinueResponse() { Type = "continue", Value = new TaskModuleTaskInfo() { Title = "More Page", Card = this.TaskModuleResponseCard(query, textValue), }, }); } }
public void TaskModuleRequestInitsWithNoArgs() { var request = new TaskModuleRequest(); Assert.NotNull(request); Assert.IsType <TaskModuleRequest>(request); }
/// <inheritdoc/> /// Handles the submit method on a change message target request. public async Task <TaskModuleResponse> SubmitAsync( ITurnContext <IInvokeActivity> turnContext, TaskModuleRequest taskModuleRequest) { var teamEntity = await this.GetTeamEntityAsync(turnContext, taskModuleRequest); var channels = await TeamsInfo.GetTeamChannelsAsync(turnContext); var messageTargetChannelName = await this.messageTargetChannelNameService.GetMessageTargetChannelNameAsync(channels, teamEntity); var whoChangedTarget = turnContext.Activity.From.Name; var displayMessage = $"{whoChangedTarget} has selected the channel, {messageTargetChannelName}, as the message target."; var reply = MessageFactory.Text(displayMessage); await turnContext.SendActivityAsync(reply); return(new TaskModuleResponse { Task = new TaskModuleMessageResponse() { Value = displayMessage, }, }); }
private async Task <TeamEntity> GetTeamEntityAsync( ITurnContext <IInvokeActivity> turnContext, TaskModuleRequest taskModuleRequest) { var requestDataAsJObject = JObject.Parse(taskModuleRequest.Data.ToString()); var selectedChannelId = requestDataAsJObject[TaskModuleConstants.ChangeMessageTargetChoiceSetInputId]?.ToString(); var teamsChannelData = turnContext.Activity.GetChannelData <TeamsChannelData>(); if (teamsChannelData == null || teamsChannelData.Team == null || string.IsNullOrWhiteSpace(teamsChannelData.Team.Id)) { throw new ApplicationException("Failed to get TeamChannelData from turn context."); } var teamEntity = await this.teamRepository.GetAsync(teamsChannelData.Team.Id); if (teamEntity == null) { throw new ApplicationException($"Failed to find the team {teamsChannelData.Team.Id} in DB"); } teamEntity.ActiveChannelId = string.IsNullOrWhiteSpace(selectedChannelId) ? null : selectedChannelId; await this.teamRepository.CreateOrUpdateAsync(teamEntity); return(teamEntity); }
/// <summary> /// Checks if its a review in a meeting action request. /// </summary> /// <param name="request">Task module request.</param> /// <returns>True if its a meeting action request, false otherwise.</returns> public static bool IsReviewInMeetingAction(this TaskModuleRequest request) { var data = request.Data as JObject; data = JObject.FromObject(data); var actionId = data["actionId"]?.ToString(); return(!string.IsNullOrEmpty(actionId) && actionId.Equals(InvokeActionType.ReviewInMeeting.ToString())); }
/// <summary> /// Invoked when task module fetch event is received from the bot. /// </summary> /// <param name="turnContext">Context object containing information cached for a single turn of conversation with a user.</param> /// <param name="taskModuleRequest">Task module invoke request value payload.</param> /// <param name="cancellationToken">Propagates notification that operations should be canceled.</param> /// <returns>A task that represents the work queued to execute.</returns> protected override async Task <TaskModuleResponse> OnTeamsTaskModuleFetchAsync( ITurnContext <IInvokeActivity> turnContext, TaskModuleRequest taskModuleRequest, CancellationToken cancellationToken) { turnContext = turnContext ?? throw new ArgumentNullException(nameof(turnContext)); taskModuleRequest = taskModuleRequest ?? throw new ArgumentNullException(nameof(taskModuleRequest)); this.RecordEvent(nameof(this.OnTeamsTaskModuleFetchAsync), turnContext); var activity = turnContext.Activity; if (taskModuleRequest.Data == null) { this.telemetryClient.TrackTrace("Request data obtained on task module fetch action is null."); await turnContext.SendActivityAsync(this.localizer.GetString("ErrorMessage")); return(null); } var postedValues = JsonConvert.DeserializeObject <AdaptiveSubmitActionData>(taskModuleRequest.Data.ToString()); var command = postedValues.Command; var userGraphAccessToken = await this.tokenHelper.GetUserTokenAsync(activity.From.Id); if (userGraphAccessToken == null && command.ToUpperInvariant() != BotCommandConstants.SeeIntroductionDetailAction) { await this.dialog.RunAsync(turnContext, this.conversationState.CreateProperty <DialogState>(nameof(DialogState)), cancellationToken); return(null); } else { switch (command.ToUpperInvariant()) { // Fetch task module to show introduction card. case BotCommandConstants.IntroductionAction: return(await this.activityHelper.GetIntroductionAsync(userGraphAccessToken, turnContext, cancellationToken)); // Fetch task module to show approve introduction card. case BotCommandConstants.ApproveIntroductionAction: return(await this.activityHelper.ApproveIntroductionActionAsync(userGraphAccessToken, turnContext)); // Fetch task module to show introduction detail card for hiring manager's team. case BotCommandConstants.SeeIntroductionDetailAction: return(this.introductionCardHelper.GetIntroductionDetailCardForTeam(postedValues.IntroductionEntity)); default: this.logger.LogInformation($"Invalid command for task module fetch activity.Command is : {command} "); await turnContext.SendActivityAsync(this.localizer.GetString("UnsupportedBotPersonalCommandText")); return(null); } } }
/// <summary> /// Invoke when user clicks on edit button on a question in SME team. /// </summary> /// <param name="turnContext">Context object containing information cached for a single turn of conversation with a user.</param> /// <param name="taskModuleRequest">Task module invoke request value payload.</param> /// <param name="cancellationToken">Propagates notification that operations should be canceled.</param> /// <returns>A task that represents the work queued to execute.</returns> /// <remarks> /// Reference link: https://docs.microsoft.com/en-us/dotnet/api/microsoft.bot.builder.teams.teamsactivityhandler.onteamstaskmodulefetchasync?view=botbuilder-dotnet-stable. /// </remarks> protected override Task <TaskModuleResponse> OnTeamsTaskModuleFetchAsync( ITurnContext <IInvokeActivity> turnContext, TaskModuleRequest taskModuleRequest, CancellationToken cancellationToken) { try { return(this.taskModuleActivity.OnFetchAsync(taskModuleRequest, this.appBaseUri)); } catch (Exception ex) { this.logger.LogError(ex, $"Error editing question : {ex.Message}", SeverityLevel.Error); return(default);
protected override async Task <TaskModuleResponse> OnTeamsTaskModuleSubmitAsync( ITurnContext <IInvokeActivity> turnContext, TaskModuleRequest taskModuleRequest, CancellationToken cancellationToken) { var asJobject = JObject.FromObject(taskModuleRequest.Data); var data = asJobject.ToString(); var reply = MessageFactory.Text("OnTeamsTaskModuleSubmitAsync Data Sent: " + data); _ = turnContext.SendActivityAsync(reply); return(null); }
/// <inheritdoc/> protected async override Task <TaskModuleResponse> OnTeamsTaskModuleSubmitAsync( ITurnContext <IInvokeActivity> turnContext, TaskModuleRequest taskModuleRequest, CancellationToken cancellationToken) { foreach (var taskModuleService in this.taskModuleServices) { if (taskModuleService.IsApplicable(taskModuleRequest)) { return(await taskModuleService.SubmitAsync(turnContext, taskModuleRequest)); } } throw new ArgumentException("No matching service can be found!"); }
/// <summary> /// Reads resource information from task module request object. /// </summary> /// <param name="request">Task module request object.</param> /// <returns><see cref="Resource"/>.</returns> public static Resource ReadResource(this TaskModuleRequest request) { var data = request.Data as JObject; data = JObject.FromObject(data); string resourceId = data["id"]?.ToString(); string resourceUrl = data["url"]?.ToString(); string resourceName = data["name"]?.ToString(); return(new Resource() { Id = resourceId, Url = resourceUrl, Name = resourceName, }); }
/// <summary> /// Invoked when task module fetch event is received from the bot. /// </summary> /// <param name="turnContext">Context object containing information cached for a single turn of conversation with a user.</param> /// <param name="taskModuleRequest">Task module invoke request value payload.</param> /// <param name="cancellationToken">Propagates notification that operations should be canceled.</param> /// <returns>A task that represents the work queued to execute.</returns> #pragma warning disable CS1998 // Overriding bot method protected override async Task <TaskModuleResponse> OnTeamsTaskModuleFetchAsync( ITurnContext <IInvokeActivity> turnContext, TaskModuleRequest taskModuleRequest, CancellationToken cancellationToken) #pragma warning restore CS1998 // Overriding bot method { try { turnContext = turnContext ?? throw new ArgumentNullException(nameof(turnContext)); taskModuleRequest = taskModuleRequest ?? throw new ArgumentNullException(nameof(taskModuleRequest)); this.RecordEvent(nameof(this.OnTeamsTaskModuleFetchAsync), turnContext); var activity = turnContext.Activity; var postedValues = JsonConvert.DeserializeObject <BotCommand>(taskModuleRequest.Data.ToString()); var command = postedValues.Text; switch (command.ToUpperInvariant()) { case Constants.ViewProjectDetail: // Messaging Extension attachment card view project details button. return(new TaskModuleResponse { Task = new TaskModuleContinueResponse { Type = "continue", Value = new TaskModuleTaskInfo() { Url = $"{this.botOptions.Value.AppBaseUri}/join-project?projectId={postedValues.ProjectId}¤tUserId={activity.From.AadObjectId}&createdByUserId={postedValues.CreatedByUserId}", Height = JoinProjectTaskModuleHeight, Width = JoinProjectTaskModuleWidth, Title = this.localizer.GetString("ApplicationName"), }, }, }); default: return(null); } } catch (Exception ex) { this.logger.LogError(ex, "Error while fetching task module received by the bot."); throw; } }
/// <summary> /// When OnTurn method receives a fetch invoke activity on bot turn, it calls this method. /// </summary> /// <param name="turnContext">Context object containing information cached for a single turn of conversation with a user.</param> /// <param name="taskModuleRequest">Task module invoke request value payload.</param> /// <param name="cancellationToken">Propagates notification that operations should be canceled.</param> /// <returns>A task that represents a task module response.</returns> /// <remarks> /// Reference link: https://docs.microsoft.com/en-us/dotnet/api/microsoft.bot.builder.teams.teamsactivityhandler.onteamstaskmodulefetchasync?view=botbuilder-dotnet-stable. /// </remarks> protected override async Task <TaskModuleResponse> OnTeamsTaskModuleFetchAsync( ITurnContext <IInvokeActivity> turnContext, TaskModuleRequest taskModuleRequest, CancellationToken cancellationToken) { try { turnContext = turnContext ?? throw new ArgumentNullException(nameof(turnContext)); this.RecordEvent(nameof(this.OnTeamsTaskModuleFetchAsync), turnContext); var activity = turnContext.Activity; var activityValue = JObject.Parse(activity.Value?.ToString())["data"].ToString(); AdaptiveSubmitActionData adaptiveSubmitActionData = JsonConvert.DeserializeObject <AdaptiveSubmitActionData>(JObject.Parse(taskModuleRequest?.Data.ToString()).SelectToken("data").ToString()); if (adaptiveSubmitActionData == null) { this.logger.LogInformation("Value obtained from task module fetch action is null"); } var adaptiveActionType = adaptiveSubmitActionData.AdaptiveActionType; var postId = adaptiveSubmitActionData.Id; switch (adaptiveActionType.ToUpperInvariant()) { case BotCommandConstants.ViewLearningModule: this.logger.LogInformation("Fetch task module to show learning module detail."); return(this.GetTaskModuleResponse(string.Format(CultureInfo.InvariantCulture, $"{this.botOptions.Value.AppBaseUri}/learningmodulepreview?viewMode=1&learningModuleId={postId}"), this.localizer.GetString("learningModuleDetails"))); case BotCommandConstants.ViewResource: this.logger.LogInformation("Fetch task module to show resource detail."); return(this.GetTaskModuleResponse(string.Format(CultureInfo.InvariantCulture, $"{this.botOptions.Value.AppBaseUri}/previewcontent?viewMode=1&resourceId={postId}"), this.localizer.GetString("resourceDetails"))); default: this.logger.LogInformation($"Invalid command for task module fetch activity. Command is: {adaptiveActionType}"); var reply = this.localizer.GetString("invalidCommand"); await turnContext.SendActivityAsync(reply).ConfigureAwait(false); return(null); } } catch (Exception ex) { this.logger.LogError(ex, "Error while fetching task module"); throw; } }
public void ModifyMenuData(TaskModuleRequest taskModuleRequest, TaskModuleTaskInfo TaskInfo) { TeamsBuyContext context = new TeamsBuyContext(); var asJobject = JObject.FromObject(taskModuleRequest.Data); var Value = asJobject.ToObject <CardTaskFetchValue <string> >()?.Data; JObject Data = JObject.Parse(JsonConvert.SerializeObject(taskModuleRequest.Data)); new OrganizeStructureService().ModifyRemoveNeedlessStructure(Data); var inputlist = new List <string>(); foreach (var item in Data) { inputlist.Add(item.Value.ToString()); } inputlist.Remove(inputlist[0]); var StoreName = inputlist[0]; inputlist.Remove(inputlist[0]); var Modify = new ModifyGroup(); var w = new List <ModifyMultiple>(); for (int i = 0; 2 * i < inputlist.Count(); i++) { w.Add(new ModifyMultiple() { ProductName = inputlist[2 * i], Amount = inputlist[2 * i + 1], MenuId = Value }); } Modify.AllModifyMultiple = w; Modify.StoreName = StoreName; for (var i = 0; i < Modify.AllModifyMultiple.Count; i++) { if (Modify.AllModifyMultiple[i].ProductName == "" || Modify.AllModifyMultiple[i].Amount.ToString() == "") { Modify.AllModifyMultiple.Remove(Modify.AllModifyMultiple[i]); } } new MenuService(context).UpdateMenuOrderStoreName(Value, Modify.StoreName); new MenuDetailService(context).DeleteMenuDetail(Value); new MenuDetailService(context).CreateMenuDetail(Modify); TaskInfo.Card = new CreateCardService().GetResultCustomizedModification(Modify.StoreName, Modify.AllModifyMultiple); SetTaskInfo(TaskInfo, TaskModuleUIConstants.UpdateMenu); }
//public Attachment GetCardAttachment(ITurnContext turnContext) //{ // var teamsContext = turnContext.TurnState.Get<ITeamsContext>(); // TaskModuleRequest query = teamsContext.GetTaskModuleRequestData(); // string textValue = null; // if (query.Data != null) // { // var data = JObject.FromObject(query.Data); // textValue = data["userText"]?.ToString(); // } // return this.GetResponseCard(query, textValue); //} // Builds the response card displayed in the task module public Attachment GetCard(TaskModuleRequest query, string textValue) { AdaptiveCards.AdaptiveCard adaptiveCard = new AdaptiveCards.AdaptiveCard(); adaptiveCard.Body.Add(new AdaptiveCards.AdaptiveTextBlock("Your Request:") { Size = AdaptiveCards.AdaptiveTextSize.Large, Weight = AdaptiveCards.AdaptiveTextWeight.Bolder, }); adaptiveCard.Body.Add(new AdaptiveCards.AdaptiveContainer() { Style = AdaptiveCards.AdaptiveContainerStyle.Emphasis, Items = new List <AdaptiveCards.AdaptiveElement> { new AdaptiveCards.AdaptiveTextBlock(JObject.FromObject(query).ToString()) { Wrap = true, }, }, }); adaptiveCard.Body.Add(new AdaptiveCards.AdaptiveTextInput() { Id = "userText", Placeholder = "Type text here...", Value = textValue, }); adaptiveCard.Actions.Add(new AdaptiveCards.AdaptiveSubmitAction() { Title = "Next", Data = JObject.Parse(@"{ ""done"": false }"), }); adaptiveCard.Actions.Add(new AdaptiveCards.AdaptiveSubmitAction() { Title = "Submit", Data = JObject.Parse(@"{ ""done"": true }"), }); return(adaptiveCard.ToAttachment()); }
public void TaskModuleRequestInits() { var data = new JObject() { { "key", "value" } }; var context = new TaskModuleRequestContext(); var tabEntityContext = new TabEntityContext(); var request = new TaskModuleRequest(data, context) { TabEntityContext = tabEntityContext }; Assert.NotNull(request); Assert.IsType <TaskModuleRequest>(request); Assert.Equal(data, request.Data); Assert.Equal(context, request.Context); Assert.Equal(tabEntityContext, request.TabEntityContext); }
/// <inheritdoc/> /// Handles the fetch method on a change message target request. public async Task <TaskModuleResponse> FetchAsync( ITurnContext <IInvokeActivity> turnContext, TaskModuleRequest taskModuleRequest) { var channels = await TeamsInfo.GetTeamChannelsAsync(turnContext); var teamsChannelData = turnContext.Activity.GetChannelData <TeamsChannelData>(); var teamEntity = await this.teamRepository.GetAsync(teamsChannelData?.Team?.Id); var messageTargetChannelId = teamEntity?.MessageTargetChannel; return(new TaskModuleResponse { Task = new TaskModuleContinueResponse { Value = new TaskModuleTaskInfo() { Title = "Setup message target channel", Width = 400, Card = this.changeMessageTargetCardRenderer.BuildAttachment(channels, messageTargetChannelId), }, }, }); }
/// <summary> /// TaskModuleSubmit. /// </summary> /// <param name="turnContext">turnContext.</param> /// <param name="taskModuleRequest">taskmoduleRequest.</param> /// <param name="cancellationToken">cancellationToken.</param> /// <returns>returns task.</returns> protected override async Task <TaskModuleResponse> OnTeamsTaskModuleSubmitAsync(ITurnContext <IInvokeActivity> turnContext, TaskModuleRequest taskModuleRequest, CancellationToken cancellationToken) { try { var activity = (Activity)turnContext.Activity; if (activity.Value == null) { throw new ArgumentException("activity's value should not be null"); } ScrumDetails scrumDetails = JsonConvert.DeserializeObject <ScrumDetails>(JObject.Parse(activity.Value.ToString())["data"].ToString()); if (string.IsNullOrEmpty(scrumDetails.Yesterday) || string.IsNullOrEmpty(scrumDetails.Today)) { return(this.GetScrumValidation(scrumDetails, turnContext, cancellationToken)); } string activityId = this.GetActivityIdToMatch(scrumDetails.MembersActivityIdMap, turnContext.Activity.From.Id); // check if member in scrum does not exists if (activityId == null) { await turnContext.SendActivityAsync(string.Format(Resources.NotPartofScrumText, turnContext.Activity.From.Name)); return(default);
/// <summary> /// TaskModuleFetch. /// </summary> /// <param name="turnContext">turnContext.</param> /// <param name="taskModuleRequest">taskmoduleRequest.</param> /// <param name="cancellationToken">cancellationToken.</param> /// <returns>returns task.</returns> protected override async Task <TaskModuleResponse> OnTeamsTaskModuleFetchAsync(ITurnContext <IInvokeActivity> turnContext, TaskModuleRequest taskModuleRequest, CancellationToken cancellationToken) { try { var activityFetch = (Activity)turnContext.Activity; if (activityFetch.Value == null) { throw new ArgumentException("activity's value should not be null"); } ScrumDetails scrumMemberDetails = JsonConvert.DeserializeObject <ScrumDetails>(JObject.Parse(activityFetch.Value.ToString())["data"].ToString()); string membersId = scrumMemberDetails.MembersActivityIdMap; string activityIdval = this.GetActivityIdToMatch(membersId, turnContext.Activity.From.Id); // A user is added during a running scrum and tries to update his/her details. if (activityIdval == null) { return(new TaskModuleResponse { Task = new TaskModuleContinueResponse { Value = new TaskModuleTaskInfo() { Card = ScrumCards.NoActionScrumCard(), Height = "small", Width = "medium", Title = Resources.NoActiveScrumTitle, }, }, }); } else { return(new TaskModuleResponse { Task = new TaskModuleContinueResponse { Value = new TaskModuleTaskInfo() { Card = ScrumCards.ScrumCard(membersId), Height = "large", Width = "medium", Title = Resources.ScrumTaskModuleTitle, }, }, }); } } catch (Exception ex) { this.telemetryClient.TrackTrace($"Invoke Activity failed: {ex.Message}"); this.telemetryClient.TrackException(ex); return(null); } }
/// <summary> /// Handle task module is submit. /// </summary> /// <param name = "turnContext" > The turn context.</param> /// <param name = "taskModuleRequest" >The task module invoke request value payload.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A Task Module Response for the request.</returns> protected override async Task <TaskModuleResponse> OnTeamsTaskModuleSubmitAsync(ITurnContext <IInvokeActivity> turnContext, TaskModuleRequest taskModuleRequest, CancellationToken cancellationToken) { var locationInfo = JObject.FromObject(taskModuleRequest.Data); var latitude = (double)locationInfo.ToObject <LocationDetails <double> >()?.Latitude; var longitude = (double)locationInfo.ToObject <LocationDetails <double> >()?.Longitude; string user = turnContext.Activity.From.Name; string time = turnContext.Activity.LocalTimestamp.ToString(); UserDetail userDetails = new UserDetail { CheckInTime = time, UserName = user, Longitude = longitude, Latitude = latitude, UserId = turnContext.Activity.From.AadObjectId }; await SaveUserDetailsAsync(turnContext, userDetails); await turnContext.SendActivityAsync(MessageFactory.Attachment(GetAdaptiveCardForUserLocation(time, user, latitude, longitude)), cancellationToken); return(null); }
/// <summary> /// Handle task module is fetch. /// </summary> /// <param name = "turnContext" > The turn context.</param> /// <param name = "taskModuleRequest" >The task module invoke request value payload.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A Task Module Response for the request.</returns> protected override Task <TaskModuleResponse> OnTeamsTaskModuleFetchAsync(ITurnContext <IInvokeActivity> turnContext, TaskModuleRequest taskModuleRequest, CancellationToken cancellationToken) { var asJobject = JObject.FromObject(taskModuleRequest.Data); var buttonType = (string)asJobject.ToObject <CardTaskFetchValue <string> >()?.Id; var taskModuleResponse = new TaskModuleResponse(); if (buttonType == "checkin") { taskModuleResponse.Task = new TaskModuleContinueResponse { Type = "continue", Value = new TaskModuleTaskInfo() { Url = _applicationBaseUrl + "/" + "CheckIn", Height = 350, Width = 350, Title = "Check in details", }, }; } else if (buttonType == "viewLocation") { var latitude = (double)asJobject.ToObject <LocationDetails <double> >()?.Latitude; var longitude = (double)asJobject.ToObject <LocationDetails <double> >()?.Longitude; taskModuleResponse.Task = new TaskModuleContinueResponse { Type = "continue", Value = new TaskModuleTaskInfo() { Url = _applicationBaseUrl + "/" + "ViewLocation?latitude=" + latitude + "&longitude=" + longitude, Height = 350, Width = 350, Title = "View location", }, }; } return(Task.FromResult(taskModuleResponse)); }
public async Task <TaskModuleResponse> GetModuleMenuData(ITurnContext <IInvokeActivity> turnContext, TaskModuleRequest taskModuleRequest, CancellationToken cancellationToken) { var TaskInfo = new TaskModuleTaskInfo(); var asJobject = JObject.FromObject(taskModuleRequest.Data); var Value = asJobject.ToObject <CardTaskFetchValue <string> >()?.Data; string GetMenuJson = new OrganizeStructureService().GetFoodUrlStr(Value); TaskInfo.Card = new OrganizeStructureService().GetTaskModuleFetchCard(Value, GetMenuJson, TaskInfo); new OrderfoodServices().SetTaskInfo(TaskInfo, TaskModuleUIConstants.AdaptiveCard); return(await Task.FromResult(TaskInfo.ToTaskModuleResponse())); }
public async Task <TaskModuleResponse> GetModifyModuleData(ITurnContext <IInvokeActivity> turnContext, TaskModuleRequest taskModuleRequest, CancellationToken cancellationToken) { var TaskInfo = new TaskModuleTaskInfo(); TeamsBuyContext context = new TeamsBuyContext(); var asJobject = JObject.FromObject(taskModuleRequest.Data); var Value = asJobject.ToObject <CardTaskFetchValue <string> >()?.Data; var MenuOrderData = new MenuDetailService(context).GetMenuOrder(Value).ToList(); var MenuOrderStore = new MenuService(context).GetMenuOrder(Value).Store; TaskInfo.Card = new CreateCardService().GetCustomizedModification(MenuOrderStore, MenuOrderData, Value); SetTaskInfo(TaskInfo, TaskModuleUIConstants.UpdateMenu); return(await Task.FromResult(TaskInfo.ToTaskModuleResponse())); }
public async Task <TaskModuleResponse> FinishSelectDishesSubmit(ITurnContext <IInvokeActivity> turnContext, TaskModuleRequest taskModuleRequest, CancellationToken cancellationToken) { TeamsBuyContext context = new TeamsBuyContext(); var TaskInfo = new TaskModuleTaskInfo(); JObject Data = JObject.Parse(JsonConvert.SerializeObject(taskModuleRequest.Data)); var StoreAndGuidAndDueTime = Data.Property("data").Value.ToString(); new OrganizeStructureService().RemoveNeedlessStructure(Data); string SelectJson = ProcessAllSelect(Data); JObject o = new JObject(); o["SelectMenu"] = JArray.Parse(SelectJson); bool DecideQuanRem = true; bool Number = true; var AllSelectDatas = JsonConvert.DeserializeObject <SelectMenuDatagroup>(o.ToString()); foreach (var item in AllSelectDatas.SelectMenu) { if (item.Quantity == "0" && item.Remarks != "") { DecideQuanRem = false; } if (Math.Sign(decimal.Parse(item.Quantity)) < 0 || (decimal.Parse(item.Quantity) - Math.Floor(decimal.Parse(item.Quantity))) != 0) { Number = false; } } if (DecideQuanRem == true && Number == true) { //取完整資料 var OAllOrderDatasStr = ProcessUnifyData(o); var SelectObject = JsonConvert.DeserializeObject <SelectAllDataGroup>(OAllOrderDatasStr); SelectObject.UserID = turnContext.Activity.From.Id; var ExistGuid = Guid.Parse("cf1ed7b9-ae4a-4832-a9f4-fdee6e492085"); new OrderDetailService(context).CreateOrderDetail(SelectObject, SelectObject.SelectAllOrders, ExistGuid); TaskInfo.Card = new CreateCardService().GetResultClickfood(new OrganizeStructureService().GetOrderID(StoreAndGuidAndDueTime), new OrganizeStructureService().GetStoreName(StoreAndGuidAndDueTime), o.ToString(), new OrganizeStructureService().GetDueTime(StoreAndGuidAndDueTime), turnContext.Activity.From.Name); SetTaskInfo(TaskInfo, TaskModuleUIConstants.AdaptiveCard); await turnContext.SendActivityAsync(MessageFactory.Attachment(new CreateCardService().GetResultClickfood(new OrganizeStructureService().GetOrderID(StoreAndGuidAndDueTime), new OrganizeStructureService().GetStoreName(StoreAndGuidAndDueTime), o.ToString(), "12:00", turnContext.Activity.From.Name))); } else { TaskInfo.Card = new CreateCardService().GetError(turnContext.Activity.From.Name); SetTaskInfo(TaskInfo, TaskModuleUIConstants.AdaptiveCard); await turnContext.SendActivityAsync(MessageFactory.Attachment(new CreateCardService().GetError(turnContext.Activity.From.Name))); } return(await Task.FromResult(TaskInfo.ToTaskModuleResponse())); }
/// <inheritdoc/> protected override Task <TaskModuleResponse> OnTeamsTaskModuleFetchAsync(ITurnContext <IInvokeActivity> turnContext, TaskModuleRequest taskModuleRequest, CancellationToken cancellationToken) { // Verify action. if (!taskModuleRequest.IsReviewInMeetingAction()) { // App doesn't recognize the action. throw new Exception("App doesn't recognize the incoming action."); } // Read resource information from task module request and return link to review it in a meeting. var resource = taskModuleRequest.ReadResource(); var response = new TaskModuleResponse(this.GetTaskModuleContinueResponse( title: resource.Name, url: $"{this.appSettings.BaseUrl}/reviewinmeeting/{resource.Id}", fallbackUrl: resource.Url)); return(Task.FromResult(response)); }
protected override Task <TaskModuleResponse> OnTeamsTaskModuleSubmitAsync(ITurnContext <IInvokeActivity> turnContext, TaskModuleRequest taskModuleRequest, CancellationToken cancellationToken) { Record.Add(MethodBase.GetCurrentMethod().Name); return(Task.FromResult(new TaskModuleResponse())); }
/// <summary> /// When OnTurn method receives a submit invoke activity on bot turn, it calls this method. /// </summary> /// <param name="turnContext">Provides context for a turn of a bot.</param> /// <param name="taskModuleRequestData">Task module invoke request value payload.</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 a task module response.</returns> protected override async Task <TaskModuleResponse> OnTeamsTaskModuleSubmitAsync(ITurnContext <IInvokeActivity> turnContext, TaskModuleRequest taskModuleRequestData, CancellationToken cancellationToken) { var valuesFromTaskModule = JsonConvert.DeserializeObject <SearchSubmitAction>(taskModuleRequestData.Data?.ToString()); try { if (valuesFromTaskModule == null) { this.logger.LogInformation($"Request data obtained on task module submit action is null."); await turnContext.SendActivityAsync(Strings.ErrorMessage).ConfigureAwait(false); return(null); } switch (valuesFromTaskModule.Command.ToUpperInvariant().Trim()) { case Constants.MyProfile: this.logger.LogInformation("Activity type is invoke submit from my profile command"); await this.rootDialog.RunAsync(turnContext, this.dialogStatePropertyAccessor, cancellationToken).ConfigureAwait(false); break; case Constants.Search: this.logger.LogInformation("Activity type is invoke submit from search command"); foreach (var profile in valuesFromTaskModule.UserProfiles) { // Bot is expected to send multiple user profile cards which may cross the threshold limit of bot messages/sec, hence adding the retry logic. await RetryPolicy.ExecuteAsync(async() => { await turnContext.SendActivityAsync(MessageFactory.Attachment(SearchCard.GetUserCard(profile)), cancellationToken).ConfigureAwait(false); }).ConfigureAwait(false); } break; } return(null); } catch (Exception ex) { this.logger.LogError(ex, "Error in submit action of task module."); return(null); } }
/// <summary> /// When OnTurn method receives a fetch invoke activity on bot turn, it calls this method. /// </summary> /// <param name="turnContext">Provides context for a turn of a bot.</param> /// <param name="taskModuleRequestData">Task module invoke request value payload.</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 a task module response.</returns> protected override async Task <TaskModuleResponse> OnTeamsTaskModuleFetchAsync(ITurnContext <IInvokeActivity> turnContext, TaskModuleRequest taskModuleRequestData, CancellationToken cancellationToken) { var activity = turnContext.Activity; var userSearchTaskModuleDetails = JsonConvert.DeserializeObject <EditProfileCardAction>(((JObject)activity.Value).GetValue("data", StringComparison.OrdinalIgnoreCase).ToString()); string command = userSearchTaskModuleDetails.Command; try { var userGraphAccessToken = await this.tokenHelper.GetUserTokenAsync(activity.From.Id, GraphResourceUri).ConfigureAwait(false); if (userGraphAccessToken == null) { await turnContext.SendActivityAsync(Strings.NotLoggedInText).ConfigureAwait(false); await this.rootDialog.RunAsync(turnContext, this.dialogStatePropertyAccessor, cancellationToken).ConfigureAwait(false); return(null); } else { switch (command) { case Constants.Search: this.logger.LogInformation("Search fetch activity called"); var apiAuthToken = this.customTokenHelper.GenerateAPIAuthToken(aadObjectId: activity.From.AadObjectId, serviceURL: activity.ServiceUrl, fromId: activity.From.Id, jwtExpiryMinutes: 60); return(new TaskModuleResponse { Task = new TaskModuleContinueResponse { Value = new TaskModuleTaskInfo() { Url = $"{this.botSettings.AppBaseUri}/?token={apiAuthToken}&telemetry={this.botSettings.AppInsightsInstrumentationKey}&theme={{theme}}", Height = TaskModuleHeight, Width = TaskModuleWidth, Title = Strings.SearchTaskModuleTitle, }, }, }); case Constants.MyProfile: this.logger.LogInformation("My profile fetch activity called"); var userProfileDetails = await this.graphApiHelper.GetUserProfileAsync(userGraphAccessToken).ConfigureAwait(false); if (userProfileDetails == null) { this.logger.LogInformation("User profile details obtained from Graph API is null."); await turnContext.SendActivityAsync(Strings.ErrorMessage).ConfigureAwait(false); return(null); } else { return(new TaskModuleResponse { Task = new TaskModuleContinueResponse { Value = new TaskModuleTaskInfo() { Card = MyProfileCard.GetEditProfileCard(userProfileDetails, userSearchTaskModuleDetails.MyProfileCardId, this.botSettings.AppBaseUri), Height = TaskModuleHeight, Width = TaskModuleWidth, Title = Strings.EditProfileTitle, }, }, }); } default: this.logger.LogInformation($"Invalid command for task module fetch activity.Command is : {command} "); await turnContext.SendActivityAsync(Strings.ErrorMessage).ConfigureAwait(false); return(null); } } } catch (Exception ex) { this.logger.LogError(ex, "Error in fetch action of task module."); return(null); } }
protected override async Task <TaskModuleTaskInfo> OnTeamsTaskModuleFetchAsync(ITurnContext <IInvokeActivity> turnContext, TaskModuleRequest taskModuleRequest, CancellationToken cancellationToken) { var reply = MessageFactory.Text("OnTeamsTaskModuleFetchAsync TaskModuleRequest: " + JsonConvert.SerializeObject(taskModuleRequest)); await turnContext.SendActivityAsync(reply, cancellationToken); var adaptiveCard = new AdaptiveCard(); adaptiveCard.Body.Add(new AdaptiveTextBlock("This is an Adaptive Card within a Task Module")); adaptiveCard.Actions.Add(new AdaptiveSubmitAction { Type = "Action.Submit", Title = "Action.Submit", Data = new JObject { { "submitLocation", "taskModule" } } }); return(new TaskModuleTaskInfo() { Card = adaptiveCard.ToAttachment(), Height = 200, Width = 400, Title = "Task Module Example", }); }