示例#1
0
        private void RenderCard(AdaptiveCard inputCard)
        {
            try
            {
                // Convert the card to be rendered to a JSON string.
                JsonObject jobj = JsonObject.Parse(inputCard.ToJson().ToString());

                // Render the card from the JSON object.
                RenderedAdaptiveCard renderedCard = _cardRendrer.RenderAdaptiveCardFromJson(jobj);

                // Get the FrameworkElement and attach it to our Frame element in the UI.
                CardFrame.Content = renderedCard.FrameworkElement;



                // Debugging check: Report any renderer warnings.
                // This includes things like an unknown element type found in the card
                // or the card exceeded the maximum number of supported actions, and so on.
                IList <IAdaptiveWarning> warnings = renderedCard.Warnings;

                for (int i = 0; i < warnings.Count; i++)
                {
                    ResultTextBox.Text += warnings[i].Message + "\n";
                }
            }
            catch (Exception ex)
            {
                // Display what went wrong.
                ResultTextBox.Text = ex.Message;
            }
        }
        public void TestSpacingAndSeparator()
        {
            AdaptiveCard card = AdaptiveCard.FromJson(@"{
  ""type"": ""AdaptiveCard"",
  ""version"": ""1.0"",
  ""body"": [
    {
      ""type"": ""TextBlock"",
      ""text"": ""Adaptive Card design session"",
      ""spacing"": ""large"",
      ""separator"": true
    }
  ]
}").Card;

            TextBlock tb = card.Body[0] as TextBlock;

            Assert.AreEqual(Spacing.Large, tb.Spacing);
            Assert.AreEqual(true, tb.Separator);

            // Assert legacy prop
#pragma warning disable 612, 618
            Assert.AreEqual(SeparationStyle.Strong, tb.Separation);
#pragma warning restore 612, 618

            string json = card.ToJson();

            Assert.IsFalse(json.Contains(@"""separator"": true"));
        }
        public async Task <ActionResult <string> > GetAdaptiveCardToChangeMessageTargetAsync(string teamId)
        {
            var teamEntity = await this.teamRepository.GetAsync(teamId);

            if (teamEntity == null)
            {
                return(this.NotFound($"Cannot find the team with id {teamId}."));
            }

            AdaptiveCard adaptiveCard = null;

            await this.turnContextService.ContinueConversationAsync(
                teamEntity,
                async (turnContext) =>
            {
                var channels        = await TeamsInfo.GetTeamChannelsAsync(turnContext);
                var targetChannelId = teamEntity.MessageTargetChannel;
                adaptiveCard        = this.changeMessageTargetCardRenderer.Build(channels, targetChannelId);
            });

            if (adaptiveCard == null)
            {
                throw new ApplicationException("Cannot build up the turn context. Failed to retrieve the message target info.");
            }

            return(adaptiveCard.ToJson());
        }
示例#4
0
文件: Card.cs 项目: RitekR/Capita
        public static Attachment CreateAdaptiveCardAttachments(string text, string message)
        {
            AdaptiveCard card = new AdaptiveCard();



            card.Body.Add(new AdaptiveTextBlock()
            {
                Text = text,
                Size = AdaptiveTextSize.Medium
            });
            card.Body.Add(new AdaptiveTextBlock()
            {
                Text = message,
                Size = AdaptiveTextSize.Medium
            });
            card.Body.Add(new AdaptiveImage()
            {
                Url   = new System.Uri("https://accelerator-origin.kkomando.com/wp-content/uploads/2016/04/shutterstock_386672542-970x546.jpg"),
                Size  = AdaptiveImageSize.Medium,
                Style = AdaptiveImageStyle.Person
            });
            string json = card.ToJson();
            //var adaptiveCardJson = File.ReadAllText(filePath);

            var adaptiveCardAttachment = new Attachment()
            {
                ContentType = "application/vnd.microsoft.card.adaptive",
                Content     = JsonConvert.DeserializeObject(json),
            };

            return(adaptiveCardAttachment);
        }
        public void TestDefaultValuesAreNotSerialized()
        {
            var card = new AdaptiveCard("1.0")
            {
                Body =
                {
                    new AdaptiveTextBlock("Hello world"),
                    new AdaptiveImage("http://adaptivecards.io/content/cats/1.png")
                }
            };

            var expected = @"{
  ""type"": ""AdaptiveCard"",
  ""version"": ""1.0"",
  ""body"": [
    {
      ""type"": ""TextBlock"",
      ""text"": ""Hello world""
    },
    {
      ""type"": ""Image"",
      ""url"": ""http://adaptivecards.io/content/cats/1.png""
    }
  ]
}";

            Assert.AreEqual(expected, card.ToJson());
        }
        /// <summary>
        /// Generates the adaptive card string for the unrecognized input.
        /// </summary>
        /// <param name="actionsTeamContext">Team context for the actions</param>
        /// <param name="userStatusForTeam">Enrollment status for the actionsTeamContext for the user</param>
        /// <param name="showAdminActions">Whether to show the admin actions</param>
        /// <returns>The adaptive card for the unrecognized input</returns>
        public static string GetCardJson(TeamContext actionsTeamContext, EnrollmentStatus userStatusForTeam, bool showAdminActions)
        {
            var messageContent = Resources.UnrecognizedInput;

            var card = new AdaptiveCard(new AdaptiveSchemaVersion(1, 0))
            {
                Body = new List <AdaptiveElement>
                {
                    new AdaptiveTextBlock()
                    {
                        Text = messageContent,
                        Wrap = true
                    }
                }
            };

            card.Actions = new List <AdaptiveAction>();

            card.Actions.AddRange(AdaptiveCardHelper.CreateUserActions(actionsTeamContext, userStatusForTeam));

            if (showAdminActions)
            {
                var adminActions = AdaptiveCardHelper.CreateAdminActions(actionsTeamContext);
                card.Actions.AddRange(adminActions);
            }

            return(card.ToJson());
        }
        private void TestSpacing(AdaptiveSpacing expected, string spacingString)
        {
            AdaptiveCard card = AdaptiveCard.FromJson(@"{
  ""type"": ""AdaptiveCard"",
  ""version"": ""1.0"",
  ""body"": [
    {
      ""type"": ""TextBlock"",
      ""text"": ""Adaptive Card design session"",
      ""spacing"": """ + spacingString + @"""
    }
  ]
}").Card;

            AdaptiveTextBlock tb = card.Body[0] as AdaptiveTextBlock;

            Assert.AreEqual(expected, tb.Spacing);

            string json = card.ToJson();
            string str  = $@"""spacing"": ""{spacingString}""";

            if (expected == AdaptiveSpacing.Default)
            {
                Assert.IsFalse(json.Contains(str));
            }
            else
            {
                Assert.IsTrue(json.Contains(str));
            }
        }
        private string BuildAdaptiveCard(Expense expense)
        {
            AdaptiveCard card = new AdaptiveCard("1.0");

            AdaptiveTextBlock title = new AdaptiveTextBlock
            {
                Text = expense.Description,
                Size = AdaptiveTextSize.Medium,
                Wrap = true
            };

            AdaptiveColumnSet columnSet = new AdaptiveColumnSet();

            AdaptiveColumn photoColumn = new AdaptiveColumn
            {
                Width = "auto"
            };

            AdaptiveImage image = new AdaptiveImage
            {
                Url   = new Uri("https://appmodernizationworkshop.blob.core.windows.net/contosoexpenses/Contoso192x192.png"),
                Size  = AdaptiveImageSize.Small,
                Style = AdaptiveImageStyle.Default
            };

            photoColumn.Items.Add(image);

            AdaptiveTextBlock amount = new AdaptiveTextBlock
            {
                Text   = expense.Cost.ToString(),
                Weight = AdaptiveTextWeight.Bolder,
                Wrap   = true
            };

            AdaptiveTextBlock date = new AdaptiveTextBlock
            {
                Text     = expense.Date.Date.ToShortDateString(),
                IsSubtle = true,
                Spacing  = AdaptiveSpacing.None,
                Wrap     = true
            };

            AdaptiveColumn expenseColumn = new AdaptiveColumn
            {
                Width = "stretch"
            };

            expenseColumn.Items.Add(amount);
            expenseColumn.Items.Add(date);

            columnSet.Columns.Add(photoColumn);
            columnSet.Columns.Add(expenseColumn);

            card.Body.Add(title);
            card.Body.Add(columnSet);

            string json = card.ToJson();

            return(json);
        }
示例#9
0
        private string CreateMediaAdaptiveCardJson()
        {
            var card = new AdaptiveCard
            {
                Version      = "1.1",
                FallbackText = "This card requires Media to be viewed. Ask your platform to update to Adaptive Cards v1.1 for this an more!"
            };

            // Create caption text.
            var caption = new AdaptiveTextBlock
            {
                Size   = TextSize.ExtraLarge,
                Weight = TextWeight.Bolder,
                Text   = "Publish Adaptive Card schema"
            };

            // Create video media.
            var media = new AdaptiveMedia
            {
                Poster = PosterUrl
            };

            media.Sources.Add(new AdaptiveMediaSource
            {
                MimeType = "video/mp4",
                Url      = MediaUrl
            });

            // Add all above to our card.
            card.Body.Add(caption);
            card.Body.Add(media);

            return(card.ToJson().ToString());
        }
示例#10
0
文件: Card.cs 项目: RitekR/Capita
        public static Attachment CreateAdaptiveCardAttachment(string text, string message)
        {
            AdaptiveCard card = new AdaptiveCard();



            card.Body.Add(new AdaptiveTextBlock()
            {
                Text = text,
                Size = AdaptiveTextSize.Medium
            });
            card.Body.Add(new AdaptiveTextBlock()
            {
                Text = message,
                Size = AdaptiveTextSize.Medium
            });
            card.Body.Add(new AdaptiveImage()
            {
                Url   = new System.Uri("https://pokerground.com/en/wp-content/uploads/2016/07/lazy-bot-poker-eng.jpg"),
                Size  = AdaptiveImageSize.Medium,
                Style = AdaptiveImageStyle.Person
            });
            string json = card.ToJson();
            //var adaptiveCardJson = File.ReadAllText(filePath);

            var adaptiveCardAttachment = new Attachment()
            {
                ContentType = "application/vnd.microsoft.card.adaptive",
                Content     = JsonConvert.DeserializeObject(json),
            };

            return(adaptiveCardAttachment);
        }
示例#11
0
        public async Task AttachTimeTableCardAsync(ITurnContext turnContext, List <Dialogs.TimeTable> datas, CancellationToken cancellationToken)
        {
            var card = new AdaptiveCard();

            card.Body.Add(new AdaptiveTextBlock
            {
                Text   = $"{LoginRequest.UserName} 님의 시간표",
                Weight = AdaptiveTextWeight.Bolder,
                HorizontalAlignment = AdaptiveHorizontalAlignment.Center,
                Size = AdaptiveTextSize.Large
            });
            card.Body.Add(new AdaptiveTextBlock
            {
                Text = DateTime.Now.ToShortDateString(),
                HorizontalAlignment = AdaptiveHorizontalAlignment.Right
            });


            foreach (var data in datas)
            {
                card.Body.Add(new AdaptiveTextBlock
                {
                    Text = $"{data.Day} - {data.StartDateTime.ToShortTimeString()} ~ {data.EndDateTime.ToShortTimeString()} : {data.Subject} - {data.Professor} - {data.Room}"
                });
            }

            var reply = MessageFactory.Attachment(new Attachment
            {
                ContentType = "application/vnd.microsoft.card.adaptive",
                Content     = JsonConvert.DeserializeObject(card.ToJson())
            });

            await turnContext.SendActivityAsync(reply, cancellationToken);
        }
示例#12
0
        private static List <Attachment> CreateAdaptiveCard(List <AdaptiveContainer> adaptiveContainers, List <AdaptiveAction> actions = null)
        {
            var attachments = new List <Attachment>();

            var card = new AdaptiveCard(new AdaptiveSchemaVersion(1, 0))
            {
                Body    = new List <AdaptiveElement>(),
                Actions = new List <AdaptiveAction>()
            };

            adaptiveContainers.ForEach(x => card.Body.Add(x));

            if (actions != null)
            {
                actions.ForEach(x => card.Actions.Add(x));
            }

            var adaptiveCardAttachment = new Attachment()
            {
                ContentType = "application/vnd.microsoft.card.adaptive",
                Content     = JsonConvert.DeserializeObject(card.ToJson()),
            };

            attachments.Add(adaptiveCardAttachment);

            return(attachments);
        }
示例#13
0
        public void DropFallbacksSerialization()
        {
            string expected = @"{
  ""type"": ""AdaptiveCard"",
  ""version"": ""1.2"",
  ""body"": [
    {
      ""type"": ""TextBlock"",
      ""text"": ""text here"",
      ""fallback"": ""drop""
    }
  ]
}";

            var parseResult = AdaptiveCard.FromJson(expected);

            Assert.AreEqual(expected, parseResult.Card.ToJson());

            var card = new AdaptiveCard("1.2")
            {
                Body =
                {
                    new AdaptiveTextBlock("text here")
                    {
                        Fallback = new AdaptiveFallbackElement(AdaptiveFallbackElement.AdaptiveFallbackType.Drop)
                    }
                }
            };
            var serializedCard = card.ToJson();

            Assert.AreEqual(expected, serializedCard);
        }
示例#14
0
        /// <summary>
        /// Creates an attachment from an adaptive card
        /// </summary>
        /// <param name="card">The adaptive card to embed in the attachment</param>
        /// <returns>The attachment</returns>
        protected Attachment CreateAdaptiveCardAttachment(AdaptiveCard card)
        {
            var adaptiveCardAttachment = new Attachment()
            {
                ContentType = AdaptiveCard.ContentType,
                Content     = JsonConvert.DeserializeObject(card.ToJson()),
            };

            return(adaptiveCardAttachment);
        }
        public void TestSerializingAdditionalData()
        {
            // Disable this warning since we want to make sure that
            // the obsoleted constructor also outputs the right version
#pragma warning disable 0618
            var card = new AdaptiveCard()
            {
                Id   = "myCard",
                Body =
                {
                    new AdaptiveTextBlock("Hello world")
                        {
                        AdditionalProperties =
                        {
                        ["-ms-shadowRadius"] = 5
                        }
                        },
                    new AdaptiveImage("http://adaptivecards.io/content/cats/1.png")
                        {
                        AdditionalProperties =
                        {
                        ["-ms-blur"] = true
                        }
                        }
                },
                AdditionalProperties =
                {
                    ["-ms-test"] = "Card extension data"
                }
            };
#pragma warning restore 0618

            var expected = @"{
  ""type"": ""AdaptiveCard"",
  ""version"": ""1.0"",
  ""id"": ""myCard"",
  ""body"": [
    {
      ""type"": ""TextBlock"",
      ""text"": ""Hello world"",
      ""-ms-shadowRadius"": 5
    },
    {
      ""type"": ""Image"",
      ""url"": ""http://adaptivecards.io/content/cats/1.png"",
      ""-ms-blur"": true
    }
  ],
  ""-ms-test"": ""Card extension data""
}";
            Assert.AreEqual(expected, card.ToJson());

            var deserializedCard = AdaptiveCard.FromJson(expected).Card;
            Assert.AreEqual(expected, deserializedCard.ToJson());
        }
        private async Task <IMessageActivity> GetAppointmentCancelCard(IDialogContext context, List <Appointment> appointments)
        {
            await context.PostAsync("Click on date to cancel the appointment");

            var adaptiveCard  = new AdaptiveCard(new AdaptiveSchemaVersion(1, 0));
            var customColumns = new List <AdaptiveColumn>()
            {
                new AdaptiveColumn()
                {
                    Items = new List <AdaptiveElement>()
                    {
                        new AdaptiveTextBlock()
                        {
                            Text     = "Appointment Date",
                            IsSubtle = true
                        }
                    }
                }
            };

            adaptiveCard.Body.Add(new AdaptiveColumnSet()
            {
                Spacing   = AdaptiveSpacing.Medium,
                Separator = true,
                Columns   = customColumns
            });

            foreach (var appointment in appointments)
            {
                adaptiveCard.Actions.Add(new AdaptiveSubmitAction()
                {
                    Title    = appointment.AppointmentDateTime.ToString(DateTimeFormatInfo.InvariantInfo),
                    DataJson = JsonConvert.SerializeObject(appointment),
                });
            }

            // serialize the card to JSON
            string json = adaptiveCard.ToJson();

            var results = AdaptiveCard.FromJson(json);
            var card    = results.Card;

            var attachment = new Attachment()
            {
                Content     = card,
                ContentType = AdaptiveCard.ContentType,
                Name        = "Appointment List"
            };

            var reply = context.MakeMessage();

            reply.Attachments.Add(attachment);
            return(reply);
        }
示例#17
0
        public void TestSerializingAdditionalData()
        {
            var card = new AdaptiveCard
            {
                Id   = "myCard",
                Body =
                {
                    new AdaptiveTextBlock("Hello world")
                        {
                        AdditionalProperties =
                        {
                        ["-ms-shadowRadius"] = 5
                        }
                        },
                    new AdaptiveImage("http://adaptivecards.io/content/cats/1.png")
                        {
                        AdditionalProperties =
                        {
                        ["-ms-blur"] = true
                        }
                        }
                },
                AdditionalProperties =
                {
                    ["-ms-test"] = "Card extension data"
                }
            };

            var expected = @"{
  ""type"": ""AdaptiveCard"",
  ""version"": ""1.0"",
  ""id"": ""myCard"",
  ""body"": [
    {
      ""type"": ""TextBlock"",
      ""text"": ""Hello world"",
      ""-ms-shadowRadius"": 5
    },
    {
      ""type"": ""Image"",
      ""url"": ""http://adaptivecards.io/content/cats/1.png"",
      ""-ms-blur"": true
    }
  ],
  ""-ms-test"": ""Card extension data""
}";

            Assert.AreEqual(expected, card.ToJson());

            var deserializedCard = AdaptiveCard.FromJson(expected).Card;

            Assert.AreEqual(expected, deserializedCard.ToJson());
        }
示例#18
0
        private dynamic singleObservationCardCreator(string date, string type, string value, string unit)
        {
            cardCreator  creator = new cardCreator();
            AdaptiveCard card    = new AdaptiveCard();

            DateTime dateFormatted = DateTime.ParseExact(date, "yyyyMMdd", null);

            card.Body.Add(creator.createTitle(type));
            card.Body.Add(creator.createSection("Observation Taken on " + dateFormatted.ToString("dd/MM/yyyy"),
                                                new string[] { type }, new string[] { value + " " + unit }));
            return(JsonConvert.DeserializeObject(card.ToJson()));
        }
示例#19
0
        //Creates a standard, more detailed card
        private dynamic standardPatientCardCreator(PatientModel patient)
        {
            cardCreator  creator = new cardCreator();
            AdaptiveCard card    = new AdaptiveCard();

            card.Body.Add(creator.createTitle("Patient Record"));

            //Create two columns; puts an image in the first one, leaves the other empty (image is intended as a user icon)
            AdaptiveColumnSet profileContainer = creator.createPhotoTextColumnSection(
                "https://www.kindpng.com/picc/m/495-4952535_create-digital-profile-icon-blue-user-profile-icon.png", 90);

            //Adds the user's name at the top
            profileContainer.Columns[1].Items.Add(new AdaptiveTextBlock()
            {
                Text   = getPatientName(patient),
                Size   = AdaptiveTextSize.Medium,
                Weight = AdaptiveTextWeight.Bolder
            });

            //Profile Section (gender, DOB, Deceased Date)
            string[] profileHeadings = { "Gender: ", "Date of Birth: ", "Deceased Date: " };
            string[] profile         =
            { patient.Gender, patient.BirthDate.ToString("dd/MM/yyyy"),
              patient.DeceasedDateTime == DateTimeOffset.MinValue ? "N/A" : patient.DeceasedDateTime.ToString("dd/MM/yyyy") };

            profileContainer.Columns[1].Items.Add(creator.createDualTextColumnSection(profileHeadings, profile));
            card.Body.Add(profileContainer);

            //Personal Information Section
            string[] personal       = { patient.MaritalStatus.Text, separatedLanguageString(patient.Communication, ",") };
            string[] personalFields = { "Marital Status:", "Languages:" };
            card.Body.Add(creator.createSection("Personal Information", personalFields, personal));

            //Medical Section
            string[] medicalFields = { "Medical Practice:", "General Practitioner:" };
            string[] medical       = { patient.gpOrganization ?? "N/A", patient.assignedGP ?? "N/A" };
            card.Body.Add(creator.createSection("Medical Information", medicalFields, medical));

            //Address Section
            string[] address =
            {
                listToDelimitedString(patient.Address[0].Line, ","), patient.Address[0].City,
                patient.Address[0].State,                      patient.Address[0].Country
            };
            card.Body.Add(creator.createSection("Address", address));

            //Contact Section
            string[] contactFields = { patient.Telecom[0].System + ":", "Use:" };
            string[] contacts      = { patient.Telecom[0].Value, patient.Telecom[0].Use };
            card.Body.Add(creator.createSection("Contact Details", contactFields, contacts));

            return(JsonConvert.DeserializeObject(card.ToJson()));
        }
示例#20
0
        public void RichTextBlock()
        {
            var card = new AdaptiveCard("1.2");

            var richTB = new AdaptiveRichTextBlock();

            richTB.HorizontalAlignment = AdaptiveHorizontalAlignment.Center;

            // Build text runs
            var textRun1 = new AdaptiveTextRun("Start the rich text block ");

            richTB.Inlines.Add(textRun1);

            var textRun2 = new AdaptiveTextRun("with some cool looking stuff");

            textRun2.Color     = AdaptiveTextColor.Accent;
            textRun2.FontStyle = AdaptiveFontStyle.Monospace;
            textRun2.IsSubtle  = true;
            textRun2.Size      = AdaptiveTextSize.Large;
            textRun2.Weight    = AdaptiveTextWeight.Bolder;
            richTB.Inlines.Add(textRun2);

            card.Body.Add(richTB);

            // Indentation needs to be kept as-is to match the result of card.ToJson
            var expected = @"{
  ""type"": ""AdaptiveCard"",
  ""version"": ""1.2"",
  ""body"": [
    {
      ""type"": ""RichTextBlock"",
      ""horizontalAlignment"": ""center"",
      ""inlines"": [
        {
          ""type"": ""TextRun"",
          ""text"": ""Start the rich text block ""
        },
        {
          ""type"": ""TextRun"",
          ""size"": ""large"",
          ""weight"": ""bolder"",
          ""color"": ""accent"",
          ""isSubtle"": true,
          ""text"": ""with some cool looking stuff"",
          ""fontStyle"": ""monospace""
        }
      ]
    }
  ]
}";

            Assert.AreEqual(expected, card.ToJson());
        }
示例#21
0
        public static string CreateSelectReceiveLocationListAdaptiveCard(List <ReceiveLocation> receiveLocations, string message, string command)
        {
            #region TopLevelColumn
            AdaptiveColumnSet topLevelColumnSet = CreateTopLevelColumnSet();
            #endregion


            #region ChoiceList

            AdaptiveChoiceSetInput choiceSetInput = new AdaptiveChoiceSetInput()
            {
                Id        = "receiveLocationsChoiceSet",
                Separator = true,
                Style     = AdaptiveChoiceInputStyle.Compact,
            };

            foreach (ReceiveLocation receiveLocation in  receiveLocations)
            {
                string name = receiveLocation.Name;

                AdaptiveChoice choice = new AdaptiveChoice()
                {
                    Title = name,
                    Value = name
                };

                choiceSetInput.Choices.Add(choice);
            }
            AdaptiveCard adaptiveCard = new AdaptiveCard();
            adaptiveCard.Body.Add(topLevelColumnSet);
            adaptiveCard.Body.Add(new AdaptiveTextBlock()
            {
                Id = "header", Text = message, Wrap = true, Color = AdaptiveTextColor.Accent, IsSubtle = true
            });
            adaptiveCard.Body.Add(choiceSetInput);
            adaptiveCard.Actions = new List <AdaptiveAction>()
            {
                new AdaptiveSubmitAction()
                {
                    Id       = "submit",
                    Title    = "Submit",
                    DataJson = "{\"command\":\"" + command + "\"}"
                }
            };

            #endregion

            string adaptiveCardJson = adaptiveCard.ToJson();
            adaptiveCardJson = RenderStaticImage(adaptiveCardJson, Constants.BizManDummyUrl, Constants.BizManImagePath);
            return(adaptiveCardJson);
        }
示例#22
0
        public void TestSerializingUnknownItems()
        {
            var card = new AdaptiveCard("1.2")
            {
                Body =
                {
                    new AdaptiveUnknownElement()
                        {
                        Type = "Graph",
                        AdditionalProperties =
                        {
                        ["UnknownProperty1"] = "UnknownValue1"
                        }
                        }
                },
                Actions =
                {
                    new AdaptiveUnknownAction()
                        {
                        Type = "Action.Graph",
                        AdditionalProperties =
                        {
                        ["UnknownProperty2"] = "UnknownValue2"
                        }
                        }
                }
            };

            var expected = @"{
  ""type"": ""AdaptiveCard"",
  ""version"": ""1.2"",
  ""body"": [
    {
      ""type"": ""Graph"",
      ""UnknownProperty1"": ""UnknownValue1""
    }
  ],
  ""actions"": [
    {
      ""type"": ""Action.Graph"",
      ""UnknownProperty2"": ""UnknownValue2""
    }
  ]
}";

            Assert.AreEqual(expected, card.ToJson());

            var deserializedCard = AdaptiveCard.FromJson(expected).Card;

            Assert.AreEqual(expected, deserializedCard.ToJson());
        }
        public void ContainerBleedSerialization()
        {
            var expected = @"{
  ""type"": ""AdaptiveCard"",
  ""version"": ""1.2"",
  ""body"": [
    {
      ""type"": ""Container"",
      ""items"": [
        {
          ""type"": ""TextBlock"",
          ""text"": ""This container has a gray background that extends to the edges of the card"",
          ""wrap"": true
        }
      ],
      ""style"": ""emphasis"",
      ""bleed"": true
    }
  ]
}";

            var card = new AdaptiveCard("1.2")
            {
                Body =
                {
                    new AdaptiveContainer()
                    {
                        Style = AdaptiveContainerStyle.Emphasis,
                        Bleed = true,
                        Items = new List <AdaptiveElement>
                        {
                            new AdaptiveTextBlock()
                            {
                                Text = "This container has a gray background that extends to the edges of the card",
                                Wrap = true
                            }
                        }
                    }
                }
            };

            var actual = card.ToJson();

            Assert.AreEqual(expected: expected, actual: actual);
            var deserializedCard   = AdaptiveCard.FromJson(expected).Card;
            var deserializedActual = deserializedCard.ToJson();

            Assert.AreEqual(expected: expected, actual: deserializedActual);
        }
示例#24
0
        private Attachment CreateAdaptiveCardAttachment(string cardName, BookingDetails booking)
        {
            AdaptiveCard card = new AdaptiveCard(new AdaptiveSchemaVersion(1, 0));

            string[] Passengers = booking.PassengerName.Split(",");

            var messageText = $"I have {booking.PassengerName} ";
            var messageBody = $"booked to {booking.Destination} from {booking.Origin} on {booking.TravelDate}.";

            card.Speak = String.Concat(messageText, messageBody);
            card.Body.Add(new AdaptiveTextBlock()
            {
                Text     = "Hello, I have",
                Type     = "TextBlock",
                Weight   = AdaptiveTextWeight.Bolder,
                IsSubtle = false,
                Size     = AdaptiveTextSize.Default
            });
            for (int i = 0; i < Passengers.Length; i++)
            {
                string res = Passengers[i];
                card.Body.Add(new AdaptiveTextBlock()
                {
                    Text = res,
                    Size = AdaptiveTextSize.Default
                });
            }

            card.Body.Add(new AdaptiveTextBlock()
            {
                Text = messageBody,
                Size = AdaptiveTextSize.Default
            });
            card.Body.Add(new AdaptiveImage()
            {
                Url = new Uri("https://adaptivecards.io/content/airplane.png")
            });

            // serialize the card to JSON
            string json = card.ToJson();

            return(new Attachment()
            {
                ContentType = "application/vnd.microsoft.card.adaptive",
                Content = JsonConvert.DeserializeObject(json),
            });
        }
示例#25
0
        void OnUserActivityRequested(UserActivityRequestManager sender, UserActivityRequestedEventArgs e)
        {
            // The system raises the UserActivityRequested event to request that the
            // app generate an activity that describes what the user is doing right now.
            // This activity is used to restore the app as part of a Set.

            using (e.GetDeferral())
            {
                // Determine which trip and to-do item the user is currently working on.
                var description = Trip.Description;
                var index       = ToDoListView.SelectedIndex;
                if (index >= 0)
                {
                    description = ToDoListView.SelectedItem.ToString();
                }

                // Generate a UserActivity that says that the user is looking at
                // a particular to-do item on this trip.
                string activityId = $"trip?id={Trip.Id}&todo={index}";
                var    activity   = new UserActivity(activityId);

                // The system uses this URI to resume the activity.
                activity.ActivationUri = new Uri($"{App.ProtocolScheme}:{activityId}");

                // Describe the activity.
                activity.VisualElements.DisplayText = Trip.Title;
                activity.VisualElements.Description = description;

                // Build the adaptive card JSON with the helper classes in the NuGet package.
                // You are welcome to generate your JSON using any library you like.
                var card = new AdaptiveCard();
                card.BackgroundImage = Trip.ImageSourceUri;
                card.Body.Add(new AdaptiveTextBlock(Trip.Title)
                {
                    Size = AdaptiveTextSize.Large, Weight = AdaptiveTextWeight.Bolder
                });
                card.Body.Add(new AdaptiveTextBlock(description));
                var adaptiveCardJson = card.ToJson();

                // Turn the JSON into an adaptive card and set it on the activity.
                activity.VisualElements.Content = AdaptiveCardBuilder.CreateAdaptiveCardFromJson(adaptiveCardJson);

                // Respond to the request.
                e.Request.SetUserActivity(activity);
            }
        }
示例#26
0
        protected override async Task OnMessageActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            var name = turnContext.Activity.Text;

            if ("help".Equals(name.ToLower()))
            {
                await turnContext.SendActivityAsync(MessageFactory.Text("Type in a VUMC member name to get people finder info", ""), cancellationToken);
            }
            else
            {
                //var name = "Ryan Clinton";
                var            names = name.Split(" ");
                HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create($"https://peoplefinder.app.vumc.org/index.jsp?action=list&Last={names[1]}&First={names[0]}&IsStaff=on&IsStudent=on&Find=Find");
                myReq.Method = "GET";

                using (HttpWebResponse response = (HttpWebResponse)myReq.GetResponse())
                {
                    if (response.StatusCode != HttpStatusCode.OK)
                    { //Something went wrong
                        throw new Exception("Something went wrong");
                    }

                    using (Stream responseStream = response.GetResponseStream())
                    {
                        if (responseStream != null)
                        {
                            using (StreamReader reader = new StreamReader(responseStream))
                            {
                                String       responseString = reader.ReadToEnd();
                                String[]     tableRows      = responseString.Split("<tr>");
                                AdaptiveCard replyCard      = ProcessRows(tableRows);

                                var reply = new Attachment()
                                {
                                    ContentType = "application/vnd.microsoft.card.adaptive",
                                    Content     = JsonConvert.DeserializeObject(replyCard.ToJson())
                                };

                                await turnContext.SendActivityAsync(MessageFactory.Attachment(reply), cancellationToken);
                            }
                        }
                    }
                }
            }
        }
示例#27
0
        private Attachment CreateAdpativeCardAttachment(MockData fakePayload)
        {
            AdaptiveCard card = new AdaptiveCard(new AdaptiveSchemaVersion(1, 0));

            card.Body.Add(new AdaptiveTextBlock()
            {
                Text = fakePayload.Title,
                Size = AdaptiveTextSize.ExtraLarge
            });

            card.Body.Add(new AdaptiveFactSet()
            {
                Type  = "FactSet",
                Facts = new List <AdaptiveFact>()
                {
                    new AdaptiveFact()
                    {
                        Title = "Id", Value = fakePayload.Id
                    },
                    new AdaptiveFact()
                    {
                        Title = "Severity", Value = fakePayload.Severity.ToString()
                    },
                    new AdaptiveFact()
                    {
                        Title = "Status", Value = fakePayload.Status
                    }
                }
            });
            card.Actions.Add(new AdaptiveSubmitAction()
            {
                Type  = "Action.Submit",
                Title = "Click me for messageBack"
            });

            string jsonObj = card.ToJson();

            Attachment attachmentCard = new Attachment()
            {
                ContentType = AdaptiveCard.ContentType,
                Content     = JsonConvert.DeserializeObject(jsonObj)
            };

            return(attachmentCard);
        }
示例#28
0
        public string CreateTestCard()
        {
            _AdaptiveCard.Body.Add(new AdaptiveTextBlock()
            {
                Text = "Hello",
                Size = AdaptiveTextSize.ExtraLarge
            });

            _AdaptiveCard.Body.Add(new AdaptiveImage()
            {
                Url = new Uri("http://adaptivecards.io/content/cats/1.png")
            });
            //_AdaptiveCard.Actions.Add();
            // serialize the card to JSON
            string json = _AdaptiveCard.ToJson();

            return(json);
        }
示例#29
0
        private static async Task SendCandidateDetailsMessage(IDialogContext context, Candidate c)
        {
            IMessageActivity reply = context.MakeMessage();

            reply.Attachments = new List <Attachment>();

            AdaptiveCard card       = CardHelper.CreateFullCardForCandidate(c);
            Attachment   attachment = new Attachment()
            {
                ContentType = AdaptiveCard.ContentType,
                Content     = card
            };

            reply.Attachments.Add(attachment);
            System.Diagnostics.Debug.WriteLine(card.ToJson());

            await context.PostAsync(reply);
        }
        public void ColumnSetStyleSerialization()
        {
            var expected = @"{
  ""type"": ""AdaptiveCard"",
  ""version"": ""1.2"",
  ""id"": ""myCard"",
  ""body"": [
    {
      ""type"": ""ColumnSet"",
      ""columns"": [],
      ""style"": ""default""
    },
    {
      ""type"": ""ColumnSet"",
      ""columns"": [],
      ""style"": ""emphasis""
    }
  ]
}";

            var card = new AdaptiveCard("1.2")
            {
                Id   = "myCard",
                Body =
                {
                    new AdaptiveColumnSet()
                    {
                        Style = AdaptiveContainerStyle.Default
                    },
                    new AdaptiveColumnSet()
                    {
                        Style = AdaptiveContainerStyle.Emphasis
                    }
                }
            };

            var actual = card.ToJson();

            Assert.AreEqual(expected: expected, actual: actual);
            var deserializedCard   = AdaptiveCard.FromJson(expected).Card;
            var deserializedActual = deserializedCard.ToJson();

            Assert.AreEqual(expected: expected, actual: deserializedActual);
        }