public async override 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 (this.Disabled?.GetValue(dc.State) == true) { return(await dc.EndDialogAsync(cancellationToken : cancellationToken).ConfigureAwait(false)); } // Get template var jTemplate = (JObject)this.Template?.GetValue(dc.State); if (jTemplate == null) { throw new Exception($"{this.Id}: a template was not provided or is not valid JSON."); } // Get data var data = this.Data?.GetValue(dc.State) ?? new JObject(); // Render card and convert to JObject var template = new AdaptiveCardTemplate(jTemplate.ToString()); var card = template.Expand(data); var jCard = !string.IsNullOrEmpty(card) ? JObject.Parse(card) : null; // Process card var result = await OnProcessCardAsync(dc, jCard, cancellationToken).ConfigureAwait(false); return(await dc.EndDialogAsync(result, cancellationToken).ConfigureAwait(false)); }
public string GetAdaptiveCard(string token) { var graphClient = GraphClient.GetGraphClient(token); var users = graphClient.Users .Request() .GetAsync().Result; string adaptiveCardJson = "{ \"$schema\": \"http://adaptivecards.io/schemas/adaptive-card.json\", \"type\": \"AdaptiveCard\", \"version\": \"1.0\", \"body\": [{ \"type\": \"ColumnSet\", \"columns\": [{ \"type\": \"Column\", \"items\": [{ \"type\": \"TextBlock\", \"weight\": \"Bolder\", \"text\": \"Group Chat Title: \", \"wrap\": true }], \"width\": \"auto\" }, { \"type\": \"Column\", \"items\": [{ \"type\": \"Input.Text\", \"placeholder\": \"Please enter the title of GroupChat\", \"wrap\": true, \"id\": \"title\" }], \"width\": \"stretch\" }] }, { \"type\": \"ColumnSet\", \"columns\": [{ \"type\": \"Column\", \"items\": [{ \"type\": \"TextBlock\", \"weight\": \"Bolder\", \"text\": \"Select Members: \", \"wrap\": true }], \"width\": \"auto\" }, { \"type\": \"Column\", \"items\": [{ \"type\": \"Input.ChoiceSet\", \"id\": \"users\", \"style\": \"compact\", \"isMultiSelect\": true, \"value\": \"\", \"choices\": [{ \"title\": \"${user1Title}\", \"value\": \"${user1Value}\" }, { \"title\": \"${user2Title}\", \"value\": \"${user2Value}\" }, { \"title\": \"${user3Title}\", \"value\": \"${user3Value}\" }, { \"title\": \"${user4Title}\", \"value\": \"${user4Value}\" }, { \"title\": \"${user5Title}\", \"value\": \"${user5Value}\" }, { \"title\": \"${user6Title}\", \"value\": \"${user6Value}\" }] }] }] }, { \"type\": \"ColumnSet\", \"columns\": [{ \"type\": \"Column\", \"items\": [{ \"type\": \"TextBlock\", \"weight\": \"Bolder\", \"text\": \"\", \"wrap\": true, \"height\": \"stretch\" }], \"width\": \"stretch\" }] },{ \"type\": \"ColumnSet\", \"columns\": [{ \"type\": \"Column\", \"items\": [{ \"type\": \"TextBlock\", \"weight\": \"Bolder\", \"text\": \"\", \"wrap\": true, \"height\": \"stretch\" }], \"width\": \"stretch\" }] },{ \"type\": \"ColumnSet\", \"columns\": [ { \"type\": \"Column\", \"items\": [ { \"type\": \"TextBlock\", \"text\": \"**Note**: Selected Members will be added into a group chat and based on the count selected, members will be added to the chat using different scenarios: with all chat history, no chat history, chat history with no. of days accordingly.\", \"height\": \"stretch\", \"wrap\": true } ], \"width\": \"stretch\" } ] } ], \"actions\": [{ \"type\": \"Action.Submit\", \"title\": \"Submit\", \"card\": { \"version\": 1.0, \"type\": \"AdaptiveCard\", \"$schema\": \"http://adaptivecards.io/schemas/adaptive-card.json\" } }] }"; // Create a Template instance from the template payload AdaptiveCardTemplate template = new AdaptiveCardTemplate(adaptiveCardJson); // You can use any serializable object as your data var payloadData = new { user1Title = users.CurrentPage[0].DisplayName, user1Value = users.CurrentPage[0].Id, user2Title = users.CurrentPage[1].DisplayName, user2Value = users.CurrentPage[1].Id, user3Title = users.CurrentPage[2].DisplayName, user3Value = users.CurrentPage[2].Id, user4Title = users.CurrentPage[3].DisplayName, user4Value = users.CurrentPage[3].Id, user5Title = users.CurrentPage[4].DisplayName, user5Value = users.CurrentPage[4].Id, user6Title = users.CurrentPage[5].DisplayName, user6Value = users.CurrentPage[5].Id, }; //"Expand" the template -this generates the final Adaptive Card payload string cardJson = template.Expand(payloadData); return(cardJson); }
public static Attachment CreatePokemonAttachment(PokemonResponse pokemon) { // combine path for cross platform support var paths = new[] { ".", "Resources", "pokemonCard.json" }; var pokemonCardJson = File.ReadAllText(Path.Combine(paths)); AdaptiveCardTemplate template = new AdaptiveCardTemplate(pokemonCardJson); pokemon.name = pokemon.name.ToUpper(); pokemon.types[0].type.name = pokemon.types[0].type.name.ToUpper(); var myData = new { pokemon = pokemon, secondType = pokemon.types.Count > 1 ? pokemon.types[1].type.name.ToUpper() : "", // esta feo esto :( hp = pokemon.stats[0].base_stat, attack = pokemon.stats[1].base_stat, defense = pokemon.stats[2].base_stat, spAttack = pokemon.stats[3].base_stat, spDefense = pokemon.stats[4].base_stat, speed = pokemon.stats[5].base_stat, }; string cardJson = template.Expand(myData); var pokemonCardAttachment = new Attachment() { ContentType = "application/vnd.microsoft.card.adaptive", Content = JsonConvert.DeserializeObject(cardJson), }; return(pokemonCardAttachment); }
/// <summary> /// Get timesheet approval notification card. /// </summary> /// <param name="cardDetails">Card details.</param> /// <returns>Timesheet approval notification card attachment.</returns> public Attachment GetApprovedNotificationCard(ApproveRejectCard cardDetails) { cardDetails = cardDetails ?? throw new ArgumentNullException(nameof(cardDetails)); var cardPayload = this.GetCardPayload(ApprovedNotificationCardCacheKey, "\\TimesheetApprovedCard\\approved-card.json"); var welcomeCardOptions = new ApproveRejectCard { TimesheetTabUrl = $"https://teams.microsoft.com/l/entity/{this.botOptions.Value.ManifestId}/fill-timesheet", Date = cardDetails.Date, ProjectLabel = this.localizer.GetString("ProjectLabel"), ProjectTitle = cardDetails.ProjectTitle, HoursLabel = this.localizer.GetString("HoursLabel"), Hours = cardDetails.Hours, CardTitle = this.localizer.GetString("TimesheetApprovedCardTitle"), StatusLabel = this.localizer.GetString("ApprovedStatus"), ViewTimesheetButtonText = this.localizer.GetString("ViewTimesheetButtonText"), }; var template = new AdaptiveCardTemplate(cardPayload); var cardJson = template.Expand(welcomeCardOptions); AdaptiveCard card = AdaptiveCard.FromJson(cardJson).Card; var adaptiveCardAttachment = new Attachment() { ContentType = AdaptiveCard.ContentType, Content = card, }; return(adaptiveCardAttachment); }
// Get incident review card send from messaging extension. public static Attachment GetIncidentReviewCard(IncidentDetails incidentDetail) { string[] paths = { ".", "Resources", "reviewCard.json" }; var adaptiveCardJson = File.ReadAllText(Path.Combine(paths)); AdaptiveCardTemplate template = new AdaptiveCardTemplate(adaptiveCardJson); var payloadData = new { incidentTitle = incidentDetail.IncidentTitle, assignedTo = incidentDetail.AssignedToName, category = incidentDetail.Category, subCategory = incidentDetail.SubCategory, createdBy = incidentDetail.CreatedBy, assignedToName = incidentDetail.AssignedToName, userMRI = incidentDetail.AssignedToMRI, incidentId = incidentDetail.IncidentId }; var cardJsonString = template.Expand(payloadData); var adaptiveCardAttachment = new Attachment() { ContentType = AdaptiveCard.ContentType, Content = JsonConvert.DeserializeObject(cardJsonString), }; return(adaptiveCardAttachment); }
/// <summary> /// This method will construct resume pair-up notification card for user. /// </summary> /// <returns>Resume pair-up notification attachment.</returns> public Attachment GetResumePairupNotificationCard() { this.logger.LogInformation("Get resume pair-up notification card initiated."); var updateMatchesCardContents = new ResumePairupMatchesCardData() { UpdateCardTitle = this.localizer.GetString("UpdateCardTitle"), UpdateCardButtonText = this.localizer.GetString("UpdateCardButtonTitle"), ConfigureMatchesCommand = Constants.ConfigureMatchesCommand, }; var cardTemplate = this.GetCardTemplate(CardCacheConstants.ResumeMatchesJsonTemplate, ResumePairUpMatchesFileName); var template = new AdaptiveCardTemplate(cardTemplate); var card = template.Expand(updateMatchesCardContents); Attachment attachment = new Attachment() { ContentType = AdaptiveCard.ContentType, Content = AdaptiveCard.FromJson(card).Card, }; this.logger.LogInformation("Get resume pair-up notification card succeeded."); return(attachment); }
/// <summary> /// This method will construct the share feedback notification card for admin team. /// </summary> /// <param name="feedbackData">User activity payload.</param> /// <param name="userDetails">User details.</param> /// <returns>Share feedback notification card attachment.</returns> public Attachment GetShareFeedbackNotificationCard(SubmitActionDataForTeamsBehavior feedbackData, TeamsChannelAccount userDetails) { this.logger.LogInformation("Get share feedback notification card initiated."); var shareFeedbackCardContents = new ShareFeedbackCardData() { FeedbackText = this.localizer.GetString("Feedback"), FeedbackSubHeaderText = this.localizer.GetString("FeedbackSubHeaderText", userDetails.GivenName), FeedbackType = feedbackData.FeedbackType, DescriptionText = this.localizer.GetString("FeedbackDescriptionTitleText"), FeedbackDescription = feedbackData.FeedbackDescription, CreatedOnText = this.localizer.GetString("CreatedOn"), FeedbackCreatedDate = DateTime.UtcNow.ToShortDateString(), ChatWithUserButtonText = this.localizer.GetString("ChatWithMatchButtonText", userDetails.GivenName), ChatInitiateURL = new Uri($"{Constants.ChatInitiateURL}?users={Uri.EscapeDataString(userDetails.UserPrincipalName)}&message={Uri.EscapeDataString(Strings.InitiateChatText)}").ToString(), }; var cardTemplate = this.GetCardTemplate(CardCacheConstants.ShareFeedbackJsonTemplate, ShareFeedbackCardFileName); var template = new AdaptiveCardTemplate(cardTemplate); var card = template.Expand(shareFeedbackCardContents); Attachment attachment = new Attachment() { ContentType = AdaptiveCard.ContentType, Content = AdaptiveCard.FromJson(card).Card, }; this.logger.LogInformation("Get share feedback notification card succeeded."); return(attachment); }
public static Attachment GetResponseAttachment(string[] filepath, InitialSequentialCard data, out string cardJsonString) { var adaptiveCardJson = File.ReadAllText(Path.Combine(filepath)); AdaptiveCardTemplate template = new AdaptiveCardTemplate(adaptiveCardJson); var payloadData = new { incidentTitle = data.action.data.IncidentTitle, assignedTo = data.action.data.AssignedTo, category = data.action.data.Category, subCategory = data.action.data.SubCategory, createdBy = data.action.data.CreatedBy, assignedToName = data.action.data.AssignedToName, userMRI = data.action.data.UserMRI, incidentId = data.action.data.IncidentId }; cardJsonString = template.Expand(payloadData); var adaptiveCardAttachment = new Attachment() { ContentType = AdaptiveCard.ContentType, Content = JsonConvert.DeserializeObject(cardJsonString), }; return(adaptiveCardAttachment); }
/// <summary> /// This method will construct the welcome notification card for personal scope. /// </summary> /// <returns>Welcome notification card attachment.</returns> public Attachment GetWelcomeNotificationCard() { this.logger.LogInformation("Get welcome notification card initiated."); var welcomeCardDataContents = new WelcomeCardData() { WelcomeTitleText = this.localizer.GetString("WelcomeTitleText"), WelcomeHeaderText = this.localizer.GetString("WelcomeHeaderText"), DiscoverGroupsBulletText = this.localizer.GetString("DiscoverGroupsBulletText"), MeetPeopleBulletText = this.localizer.GetString("MeetPeopleBulletText"), GetAnswersBulletText = this.localizer.GetString("GetAnswersBulletText"), AboutGroupsBulletText = this.localizer.GetString("AboutGroupsBulletText"), DiscoverGroupsButtonText = this.localizer.GetString("DiscoverGroupsButtonText"), DiscoverGroupsUrl = new Uri($"{TabRedirectionUrl}/{this.botOptions.Value.ManifestId}/{TabEntityId}").ToString(), }; var cardTemplate = this.GetCardTemplate(CardCacheConstants.WelcomeJsonTemplate, WelcomeCardFileName); var template = new AdaptiveCardTemplate(cardTemplate); var card = template.Expand(welcomeCardDataContents); Attachment attachment = new Attachment() { ContentType = AdaptiveCard.ContentType, Content = AdaptiveCard.FromJson(card).Card, }; this.logger.LogInformation("Get welcome notification card succeeded."); return(attachment); }
public static Attachment AgendaAdaptiveList(TaskInfo taskInfo, string jsonFileName, int?percentOption1, int?percentOption2) { string[] type = { ".", "Resources", jsonFileName }; var adaptiveCard = System.IO.File.ReadAllText(Path.Combine(type)); // Create a Template instance from the template payload AdaptiveCardTemplate template = new AdaptiveCardTemplate(adaptiveCard); // You can use any serializable object as your data var payloadData = new { Title = taskInfo.title, option1 = taskInfo.option1, option2 = taskInfo.option2, Id = taskInfo.id, percentoption1 = percentOption1, percentoption2 = percentOption2 }; //"Expand" the template -this generates the final Adaptive Card payload string cardJson = template.Expand(payloadData); var adaptiveCardAttachmnt = new Attachment() { ContentType = "application/vnd.microsoft.card.adaptive", Content = JsonConvert.DeserializeObject(cardJson), }; return(adaptiveCardAttachmnt); }
private static Attachment GetPayloadBasedOnCardType(string[] type, BlobDataDeserializer blobData, string cardStatusImg, out string cardJsonstring) { var adaptiveCard = File.ReadAllText(Path.Combine(type)); AdaptiveCardTemplate template = new AdaptiveCardTemplate(adaptiveCard); var payloadData = new { originatorId = Constants.OriginatorId, requestID = blobData.requestID, userMRI = blobData.assignedToId, cardTitle = "Request " + blobData.status, cardStatusImg = cardStatusImg, status = blobData.status, itemName = blobData.itemName, itemCode = blobData.itemCode, assignedToImg = blobData.assignedToUserImage, assignedToName = blobData.assignedToName, submittedByImg = blobData.submittedByUserImage, submittedByName = blobData.submittedByName, imagesCount = blobData.imageURL.Count, mailViewDetailsUrl = Constants.BaseUrl + "/ViewDetails?id=" + blobData.requestID }; cardJsonstring = template.Expand(payloadData); var adaptiveCardAttachmnt = new Attachment() { ContentType = AdaptiveCard.ContentType, Content = JsonConvert.DeserializeObject(cardJsonstring), }; return(adaptiveCardAttachmnt); }
private static Attachment GetPayloadBasedOnCardType(string[] type, IConfiguration configuration) { var adaptiveCard = File.ReadAllText(Path.Combine(type)); // Create a Template instance from the template payload AdaptiveCardTemplate template = new AdaptiveCardTemplate(adaptiveCard); var assetDetails = Common.GetAssetDetails(configuration); // You can use any serializable object as your data var payloadData = new { approverName = assetDetails.Result.ApproverName, submittedBy = assetDetails.Result.SubmittedBy, dateOfSubmission = assetDetails.Result.DateOfSubmission, submittedTo = assetDetails.Result.SubitteTo, docName = assetDetails.Result.DocName, url = assetDetails.Result.url, userMRI = assetDetails.Result.userMRI, userChat = assetDetails.Result.userChat }; //"Expand" the template -this generates the final Adaptive Card payload string cardJson = template.Expand(payloadData); var adaptiveCardAttachmnt = new Attachment() { ContentType = "application/vnd.microsoft.card.adaptive", Content = JsonConvert.DeserializeObject(cardJson), }; return(adaptiveCardAttachmnt); }
// Get response attachment private Attachment GetResponseAttachment(string[] filepath, InitialSequentialCard data, out string cardJsonString) { var adaptiveCardJson = File.ReadAllText(Path.Combine(filepath)); AdaptiveCardTemplate template = new AdaptiveCardTemplate(adaptiveCardJson); var payloadData = new { requestTitle = data.action.data.RequestTitle, requestDescription = data.action.data.RequestDescription, assignedTo = data.action.data.AssignedTo, createdBy = data.action.data.CreatedBy, assignedToName = data.action.data.AssignedToName, userMRI = data.action.data.UserMRI, userId = data.action.data.UserId, createdById = data.action.data.CreatedById, }; //"Expand" the template -this generates the final Adaptive Card payload cardJsonString = template.Expand(payloadData); var adaptiveCardAttachment = new Attachment() { ContentType = "application/vnd.microsoft.card.adaptive", Content = JsonConvert.DeserializeObject(cardJsonString), }; return(adaptiveCardAttachment); }
// Get next card. private AdaptiveCardInvokeResponse GetNextActionCard(string[] path, InitialSequentialCard data) { var cardJson = File.ReadAllText(Path.Combine(path)); AdaptiveCardTemplate template = new AdaptiveCardTemplate(cardJson); var payloadData = new { requestTitle = data.action.data.RequestTitle, requestDescription = data.action.data.RequestDescription, assignedTo = data.action.data.AssignedTo, createdBy = data.action.data.CreatedBy, createdById = data.action.data.CreatedById, assignedToName = data.action.data.AssignedToName, userMRI = data.action.data.UserMRI }; //"Expand" the template -this generates the final Adaptive Card payload var cardJsonstring = template.Expand(payloadData); var card = JObject.Parse(cardJsonstring); var adaptiveCardResponse = new AdaptiveCardInvokeResponse() { StatusCode = 200, Type = "application/vnd.microsoft.card.adaptive", Value = card }; return(adaptiveCardResponse); }
/// <summary> /// Get team posts result for Messaging Extension. /// </summary> /// <param name="resourceList">List of user search result.</param> /// <returns><see cref="Task"/>Returns Messaging Extension result object, which will be used for providing the card.</returns> private async Task <MessagingExtensionResult> GetLearningModuleResultAsync(IEnumerable <LearningModule> resourceList) { MessagingExtensionResult composeExtensionResult = new MessagingExtensionResult { Type = "result", AttachmentLayout = AttachmentLayoutTypes.List, Attachments = new List <MessagingExtensionAttachment>(), }; if (resourceList == null) { return(composeExtensionResult); } foreach (var resource in resourceList) { var resourceModuleMapping = await this.unitOfWork.ResourceModuleRepository.FindAsync(resourceModule => resourceModule.LearningModuleId == resource.Id); var learningModuleDetails = new LearningModuleCardViewModel { ImageUrl = resource.ImageUrl, Title = resource.Title, Description = resource.Description.Trim().Length > Constants.LearningModuleCardDescriptionLength ? $"{resource.Description.Trim().Substring(0, Constants.ResourceCardDescriptionLength)}..." : resource.Description.Trim(), GradeLabel = this.localizer.GetString("grade"), GradeName = resource.Grade.GradeName, SubjectLabel = this.localizer.GetString("subject"), SubjectName = resource.Subject.SubjectName, Id = resource.Id, ViewDetailLabel = this.localizer.GetString("viewDetail"), TaskModuleData = new AdaptiveSubmitActionData { AdaptiveActionType = BotCommandConstants.ViewLearningModule, Id = resource.Id.ToString() }, ResourceCount = resourceModuleMapping.Count(), }; var cardPayload = this.GetCardPayload(CacheKeysConstants.LearningModuleCardJSONTemplate, "LearningModuleCard.json"); var template = new AdaptiveCardTemplate(cardPayload); var card = template.Expand(learningModuleDetails); AdaptiveCard adaptiveCard = AdaptiveCard.FromJson(card).Card; ThumbnailCard previewCard = new ThumbnailCard { Images = new List <CardImage> { new CardImage(resource.ImageUrl), }, Title = $"<p style='font-weight: 600;font-size: 14px;'>{HttpUtility.HtmlEncode(resource.Title)}</p>", Text = $"<p style='font-size: 14px;'>{HttpUtility.HtmlEncode(resource.Subject.SubjectName)} | {HttpUtility.HtmlEncode(resource.Grade.GradeName)} | {HttpUtility.HtmlEncode(resourceModuleMapping.Count())} items</p>", }; composeExtensionResult.Attachments.Add(new Attachment { ContentType = AdaptiveCard.ContentType, Content = adaptiveCard, }.ToMessagingExtensionAttachment(previewCard.ToAttachment())); } return(composeExtensionResult); }
public ActionResult Put(string id, [FromBody] Incident incident) { try { // load adaptive card template from file (this file is in this solution, so change it as you see fit) // use https://adaptivecards.io/designer/ to design the template JObject jsonObject = JObject.Parse(System.IO.File.ReadAllText(configuration["AdaptiveCardTemplatePath"])); AdaptiveCardTemplate template = new AdaptiveCardTemplate(jsonObject); // apply incident data from request to template string card = template.Expand(incident); //TODO: have them pass id AND activityid instead? string messageId = id.Split(";messageid=")[1]; // make call to Teams REST API to UPDATE an EXISTING message in a channel var updateUrl = $"{configuration["ConversationsUrl"]}/{id}/activities/{messageId}"; using (var requestMessage = new HttpRequestMessage(HttpMethod.Put, updateUrl)) { requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", botAccessToken); var payloadString = "{" + "\"type\": \"message\"," + "\"text\": \"\"," + "\"attachments\": [" + "{" + "\"contentType\": \"application/vnd.microsoft.card.adaptive\"," + "\"content\": " + card + "" + "}" + "]," + "\"entities\": []" + "}" + "}"; requestMessage.Content = new StringContent(payloadString, Encoding.UTF8, "application/json"); using (var sendResponse = httpClient.SendAsync(requestMessage).Result) { if (sendResponse.StatusCode == HttpStatusCode.OK) { var jsonResponseString = sendResponse.Content.ReadAsStringAsync().Result; return(Ok(jsonResponseString)); } else { return(StatusCode((int)sendResponse.StatusCode, sendResponse)); } } } } catch (Exception ex) { return(StatusCode(500, ex)); } }
public string Render() { var template = new AdaptiveCardTemplate(Template); var expanded = template.Expand(Data); var card = AdaptiveCard.FromJson(expanded); var renderer = new HtmlCardRenderer(); var output = renderer.RenderCard(card.Card); return(output.Html.ToString()); }
/// <summary> /// This method will construct the QnA response notification card for user. /// </summary> /// <param name="question">Question from the user.</param> /// <param name="answer">Knowledge base answer from QnA maker service.</param> /// <param name="prompts">Prompts associated with the current question.</param> /// <param name="appBaseUri">The base URI where the App is hosted.</param> /// <returns>QnA response notification card attachment.</returns> public Attachment GetQnAResponseNotificationCard(string question, string answer, IList <PromptDTO> prompts, string appBaseUri) { this.logger.LogInformation("Get QnA response notification card initiated."); var qnAResponseCardContents = new QnAResponseCardData() { ResponseHeaderText = this.localizer.GetString("ResponseHeaderText"), QuestionText = question, AnswerText = answer, IsPromptQuestionsPresent = prompts.Count > 0, PromptHeaderText = this.localizer.GetString("PromptHeaderText"), ShareFeedbackButtonText = this.localizer.GetString("ShareFeedbackText"), FeedbackHeaderText = this.localizer.GetString("FeedbackHeaderText"), FeedbackTitleText = this.localizer.GetString("FeedbackTitleText"), HelpfulTitleText = this.localizer.GetString("HelpfulTitleText"), NeedsImprovementTitleText = this.localizer.GetString("NeedsImprovementTitleText"), NotHelpfulTitleText = this.localizer.GetString("NotHelpfulTitleText"), ChoiceSetPlaceholder = this.localizer.GetString("ChoiceSetPlaceholder"), DescriptionText = this.localizer.GetString("FeedbackDescriptionTitleText"), DescriptionPlaceHolderText = this.localizer.GetString("DescriptionPlaceHolderText"), ShareButtonText = this.localizer.GetString("ShareButtonText"), ShareCommand = Constants.ShareCommand, }; if (prompts.Count != 0) { var promptLimit = prompts.Count > MaximumPromptQuestionCount?prompts.Take(MaximumPromptQuestionCount) : prompts; qnAResponseCardContents.ColumnSets = new List <ColumnData>(); foreach (var prompt in promptLimit) { qnAResponseCardContents.ColumnSets.Add(new ColumnData() { ImageUrl = new Uri($"{appBaseUri}/Artifacts/Info.png"), PromptQuestion = prompt.DisplayText, }); } } var cardTemplate = this.GetCardTemplate(CardCacheConstants.QnAResponseJsonTemplate, QnAResponseCardFileName); var template = new AdaptiveCardTemplate(cardTemplate); var card = template.Expand(qnAResponseCardContents); Attachment attachment = new Attachment() { ContentType = AdaptiveCard.ContentType, Content = AdaptiveCard.FromJson(card).Card, }; this.logger.LogInformation("Get QnA response notification card succeeded."); return(attachment); }
/// <summary> /// Creates the pair-up notification card. /// </summary> /// <param name="sender">The user who will be sending this card.</param> /// <param name="recipient">The user who will be receiving this card.</param> /// <param name="teamId">Team id.</param> /// <param name="teamName">Team Name.</param> /// <param name="functionAppDirectory">Function app directory.</param> /// <param name="log">The logger.</param> /// <returns>Pair-up notification card.</returns> private Attachment GetPairUpNotificationCard( UserData sender, UserData recipient, string teamId, string teamName, string functionAppDirectory, ILogger log) { sender = sender ?? throw new ArgumentNullException(nameof(sender)); recipient = recipient ?? throw new ArgumentNullException(nameof(recipient)); log.LogInformation("Get pair-up notification card initiated."); var meetingTitle = this.localizer.GetString("MeetupTitle"); var meetingContent = this.localizer.GetString("MeetupContent", this.localizer.GetString("AppTitle")); var meetingLink = $"{MeetingLink}{Uri.EscapeDataString(meetingTitle)}&attendees={recipient.UserPrincipalName}&content={Uri.EscapeDataString(meetingContent)}"; var pairUpCardContents = new PairUpNotificationCardData() { MatchUpCardTitleText = this.localizer.GetString("MatchUpCardTitleContent"), MatchUpCardSubHeaderText = this.localizer.GetString("MatchUpCardMatchedText"), MatchUpCardContent = this.localizer.GetString("MatchUpCardContentPart1", recipient.UserGivenName, teamName), ChatWithUserButtonText = this.localizer.GetString("ChatWithMatchButtonText", recipient.UserGivenName), ChatInitiateURL = new Uri($"{ChatInitiateURL}?users={Uri.EscapeDataString(recipient.UserPrincipalName)}&message={Uri.EscapeDataString(this.localizer.GetString("InitiateChatText"))}").ToString(), ProposeMeetupButtonText = this.localizer.GetString("ProposeMeetupButtonText"), MeetingLink = new Uri(meetingLink).ToString(), PauseMatchesButtonText = this.localizer.GetString("PauseMatchesButtonText"), PauseMatchesText = PauseMatchesCommand, TeamId = teamId, }; // Get pair up notification card template. bool isCacheEntryExists = this.memoryCache.TryGetValue(PairUpCardJsonTemplate, out string pairUpNotificationCardTemplate); if (!isCacheEntryExists) { var cardJsonFilePath = Path.Combine(functionAppDirectory, $".\\Cards\\{PairUpNotificationCardFileName}"); pairUpNotificationCardTemplate = File.ReadAllText(cardJsonFilePath); this.memoryCache.Set(PairUpCardJsonTemplate, pairUpNotificationCardTemplate); } var template = new AdaptiveCardTemplate(pairUpNotificationCardTemplate); var card = template.Expand(pairUpCardContents); AdaptiveCard adaptiveCard = AdaptiveCard.FromJson(card).Card; Attachment attachment = new Attachment() { ContentType = AdaptiveCard.ContentType, Content = adaptiveCard, }; log.LogInformation("Get pair-up notification card succeeded."); return(attachment); }
public string AsJson <T>(T data) { var cardJson = AsJson(); var cardData = JsonConvert.SerializeObject(data); AdaptiveCardTemplate template = new AdaptiveCardTemplate(cardJson); return(template.Expand(cardData)); //var transformer = new AdaptiveTransformer(); //return transformer.Transform(cardJson, cardData); }
/// <summary> /// Get approval notification card attachment. /// </summary> /// <param name="groupEntity">Employee resource group entity.</param> /// <param name="groupCreatorName">Group creator name.</param> /// <param name="approvalStatusText">Represents the approval status text.</param> /// <returns>Approval notification card attachment.</returns> public Attachment GetApprovalCard(EmployeeResourceGroupEntity groupEntity, string groupCreatorName, string approvalStatusText = null) { string cardTemplate; this.logger.LogInformation("Get approval card initiated."); var approvalCardContents = new ApprovalCardData() { RequestSubmittedText = this.localizer.GetString("ApproveCardRequestSubmitted"), ApprovalStatusText = string.IsNullOrEmpty(approvalStatusText) ? this.localizer.GetString("PendingApprovalText") : approvalStatusText, ApprovalStatus = groupEntity.ApprovalStatus.ToString(), GroupDescriptionText = groupEntity.GroupDescription, NameText = this.localizer.GetString("NameText"), GroupNameText = groupEntity.GroupName, TagsText = this.localizer.GetString("TagText"), ApproveTagsName = !string.IsNullOrEmpty(groupEntity.Tags) ? string.Join(", ", JsonConvert.DeserializeObject <List <string> >(groupEntity.Tags)) : string.Empty, LocationText = this.localizer.GetString("LocationText"), LocationName = groupEntity.Location, CreatedByNameText = this.localizer.GetString("CreatedByNameText"), CreatedByName = groupCreatorName, SearchEnableText = this.localizer.GetString("SearchEnabledText"), SearchEnableStatusText = groupEntity.IncludeInSearchResults ? this.localizer.GetString("YesText") : this.localizer.GetString("NoText"), ApproveButtonText = this.localizer.GetString("ApproveButtonText"), RejectButtonText = this.localizer.GetString("RejectButtonText"), ApprovedCommandText = Constants.ApprovedText, RejectCommandText = Constants.RejectedText, GroupId = groupEntity.GroupId, }; if (groupEntity.ApprovalStatus == (int)ApprovalStatus.PendingForApproval) { cardTemplate = this.GetCardTemplate(CardCacheConstants.AdminNotificationCardJsonTemplate, ApprovalCardFileName); } else { cardTemplate = this.GetCardTemplate(CardCacheConstants.AdminApprovalCardJsonTemplate, ApprovalUpdatedCardFileName); } var template = new AdaptiveCardTemplate(cardTemplate); var card = template.Expand(approvalCardContents); AdaptiveCard adaptiveCard = AdaptiveCard.FromJson(card).Card; Attachment attachment = new Attachment() { ContentType = AdaptiveCard.ContentType, Content = adaptiveCard, }; this.logger.LogInformation("Get approval card succeeded."); return(attachment); }
/// <summary> /// Creates an adaptive card for the given template and binds multiple object data to it. /// </summary> /// <param name="templateName">The file name of the adaptive card template.</param> /// <param name="dataObject">The object containing data to bind to the card. Optional.</param> /// <returns>An <see cref="AdaptiveCard"/> created from the template and data objects.</returns> private static AdaptiveCard GetAdaptiveCard(string templateName, object dataObject = null) { var cardPath = Path.Combine("Resources", "Cards", templateName); var consultCardJson = File.ReadAllText(cardPath, Encoding.UTF8); // Expand card using data object (if provided) if (dataObject != null) { var adaptiveCardTemplate = new AdaptiveCardTemplate(consultCardJson); consultCardJson = adaptiveCardTemplate.Expand(dataObject); } return(AdaptiveCard.FromJson(consultCardJson).Card); }
/// <summary> /// Creates an adaptive card for the given template and bind the object data to it. /// </summary> /// <param name="templateName">The adaptive card template.</param> /// <param name="data">The object containing the data to bind to the card.</param> /// <returns></returns> public static AdaptiveCard GetAdaptiveCard(string templateName, object data) { var cardResourcePath = "WriteThatDownBot.Cards." + templateName; using (var stream = typeof(NoteCardFactory).Assembly.GetManifestResourceStream(cardResourcePath)) { using (var reader = new StreamReader(stream)) { var cardJson = reader.ReadToEnd(); var cardTemplate = new AdaptiveCardTemplate(cardJson); return(JsonConvert.DeserializeObject <AdaptiveCard>(cardTemplate.Expand(data))); } } }
private Attachment GetResponseAttachment(string[] filepath, object data, out string cardJsonString) { var adaptiveCardJson = File.ReadAllText(Path.Combine(filepath)); AdaptiveCardTemplate template = new AdaptiveCardTemplate(adaptiveCardJson); cardJsonString = template.Expand(data); var adaptiveCardAttachment = new Attachment() { ContentType = "application/vnd.microsoft.card.adaptive", Content = JsonConvert.DeserializeObject(cardJsonString), }; return(adaptiveCardAttachment); }
// Get incident list card. public static Attachment GetInicidentListCard(IncidentList incidentList) { //Read the card json and create attachment. string[] paths = { ".", "Resources", "incidentListCard.json" }; var adaptiveCardJson = File.ReadAllText(Path.Combine(paths)); AdaptiveCardTemplate template = new AdaptiveCardTemplate(adaptiveCardJson); var cardJsonstring = template.Expand(incidentList); var adaptiveCardAttachment = new Attachment() { ContentType = AdaptiveCard.ContentType, Content = JsonConvert.DeserializeObject(cardJsonstring) }; return(adaptiveCardAttachment); }
/// <inheritdoc/> public Attachment CreateAdaptiveCardAttachement(string filePath, object dataObj) { var cardJSON = File.ReadAllText(filePath); if (dataObj != null) { AdaptiveCardTemplate template = new AdaptiveCardTemplate(cardJSON); cardJSON = template.Expand(dataObj); } var adaptiveCardAttachment = new Attachment { ContentType = AdaptiveCard.ContentType, Content = JsonConvert.DeserializeObject(cardJSON), }; return(adaptiveCardAttachment); }
/// <summary> /// Method to get First options Adaptive card. /// </summary> /// <param name="filepath"></param> /// <param name="name"></param> /// <param name="userMRI"></param> /// <returns></returns> public static Attachment GetFirstOptionsAdaptiveCard(string[] filepath, string name = null, string userMRI = null) { var adaptiveCardJson = File.ReadAllText(Path.Combine(filepath)); AdaptiveCardTemplate template = new AdaptiveCardTemplate(adaptiveCardJson); var payloadData = new { createdById = userMRI, createdBy = name }; var cardJsonstring = template.Expand(payloadData); var adaptiveCardAttachment = new Attachment() { ContentType = AdaptiveCard.ContentType, Content = JsonConvert.DeserializeObject(cardJsonstring), }; return(adaptiveCardAttachment); }
private async Task <IMessageActivity> CreateReplyActivityAsync(ChannelAccount user) { var templatePath = Path.Combine(".", "Resources", "EchoCard.json"); var templateJson = await File.ReadAllTextAsync(templatePath); var template = new AdaptiveCardTemplate(templateJson); var cardJson = template.Expand(new { Id = user.Id, Name = user.Name }); var attachment = new Attachment() { ContentType = "application/vnd.microsoft.card.adaptive", Content = JsonConvert.DeserializeObject(cardJson), }; return(MessageFactory.Attachment(attachment)); }
/// <summary> /// Creates the adaptive card from by processing template and related data /// </summary> /// <param name="template">Adaptive template</param> /// <param name="cardData">card data to merge into template</param> /// <returns>Card attachment</returns> protected static Attachment GetCard(AdaptiveCardTemplate template, dynamic cardData) { // "Expand" the template - this generates the final Adaptive Card payload var cardJson = template.Expand(cardData); try { var welcomeCard = AdaptiveCard.FromJson(cardJson); return(new Attachment { ContentType = AdaptiveCard.ContentType, Content = welcomeCard.Card, }); } catch (Exception) { return(null); } }
private Attachment GetAdaptiveCardAttachment(string fileName, object cardData) { var templateJson = File.ReadAllText("./Cards/" + fileName); AdaptiveCardTemplate template = new AdaptiveCardTemplate(templateJson); string cardJson = template.Expand(cardData); AdaptiveCardParseResult result = AdaptiveCard.FromJson(cardJson); // Get card from result AdaptiveCard card = result.Card; var adaptiveCardAttachment = new Attachment { ContentType = AdaptiveCard.ContentType, Content = card, }; return(adaptiveCardAttachment); }