protected override void Render() { if (CardJson == null) { CardFrameworkElement = null; return; } try { var renderer = new AdaptiveCardRenderer(); if (HOST_CONFIG_JSON != null) { var hostParseResult = AdaptiveHostConfig.FromJsonString(HOST_CONFIG_JSON); if (hostParseResult.HostConfig != null) { renderer.HostConfig = hostParseResult.HostConfig; } } var renderedCard = renderer.RenderAdaptiveCardFromJsonString(CardJson); CardFrameworkElement = renderedCard.FrameworkElement; } catch { } }
public MainWindow() { this.InitializeComponent(); this.Dispatcher.UnhandledException += this.Dispatcher_UnhandledException; CommandBinding cb = new CommandBinding(ApplicationCommands.Copy, this.CopyCmdExecuted, this.CopyCmdCanExecute); this.ConversationView.ConversationHistory.CommandBindings.Add(cb); this.ActivitiesPane.CommandBindings.Add(cb); this.ActivityPayloadPane.CommandBindings.Add(cb); this.DataContext = this; this.player.PlaybackStopped += this.Player_PlaybackStopped; Services.Tracker.Configure(this.settings).Apply(); this.renderer = new AdaptiveCardRenderer(); /* * Xceed Enhanced Input Package * This optional package enhances the Adaptive Card input controls beyond what WPF provides out of the box. * To enable it: * 1. Add the NuGet package Extended.Wpf.Toolkit by Xceed to the project * 2. Add the NuGet package AdaptiveCards.Rendering.Wpf.Xceed by Microsoft to the project * 3. Uncomment the one line below * This option is not included here because of its license terms. * For more info: https://docs.microsoft.com/en-us/adaptive-cards/sdk/rendering-cards/net-wpf/getting-started */ // this.renderer.UseXceedElementRenderers(); var configFile = Path.Combine(System.Reflection.Assembly.GetExecutingAssembly().Location, "AdaptiveCardsHostConfig.json"); if (File.Exists(configFile)) { this.renderer.HostConfig = AdaptiveHostConfig.FromJson(File.ReadAllText(configFile)); } }
public AdaptiveRenderContext(AdaptiveHostConfig hostConfig, AdaptiveElementRenderers <HtmlTag, AdaptiveRenderContext> elementRenderers) { // clone it Config = JsonConvert.DeserializeObject <AdaptiveHostConfig>(JsonConvert.SerializeObject(hostConfig)); ElementRenderers = elementRenderers; ForegroundColors = Config.ContainerStyles.Default.ForegroundColors; }
public static void InitializeRenderer(AdaptiveHostConfig hostConfig) { _renderer = new AdaptiveCardRenderer(); if (hostConfig != null) { _renderer.HostConfig = hostConfig; } // Add a feature representing this version of the visualizer. used for test cards. _renderer.FeatureRegistration.Set("acTest", "1.0"); if (Settings.UseFixedDimensions) { _renderer.SetFixedDimensions(320, 180); } // Custom resource resolvers _renderer.ResourceResolvers.Set("symbol", new MySymbolResourceResolver()); /* * Example on how to override the Action Positive and Destructive styles * Style positiveStyle = new Style(typeof(Button)); * positiveStyle.Setters.Add(new Setter(Button.BackgroundProperty, new SolidColorBrush(Windows.UI.Colors.LawnGreen))); * Style destructiveStyle = new Style(typeof(Button)); * destructiveStyle.Setters.Add(new Setter(Button.BackgroundProperty, new SolidColorBrush(Windows.UI.Colors.Red))); * Style otherStyle = new Style(typeof(Button)); * otherStyle.Setters.Add(new Setter(Button.BackgroundProperty, new SolidColorBrush(Windows.UI.Colors.Yellow))); * otherStyle.Setters.Add(new Setter(Button.ForegroundProperty, new SolidColorBrush(Windows.UI.Colors.DarkRed))); * * _renderer.OverrideStyles = new ResourceDictionary(); * _renderer.OverrideStyles.Add("Adaptive.Action.Positive", positiveStyle); * _renderer.OverrideStyles.Add("Adaptive.Action.Destructive", destructiveStyle); * _renderer.OverrideStyles.Add("Adaptive.Action.other", otherStyle); */ }
public MainView() { DataContextChanged += MainView_DataContextChanged; InitializeComponent(); string json; try { var fileHelper = IoC.Get <IFileHelper>(); json = fileHelper.ReadTextFile(fileHelper.ActualPath + "Assets/WindowsNotificationHostConfig.json"); } catch { json = null; } if (json == null) { _renderer = new AdaptiveCardRenderer(); } else { var hostConfig = AdaptiveHostConfig.FromJson(json); _renderer = new AdaptiveCardRenderer(hostConfig); } _card = CreateCard(); }
public AdaptiveRenderContext(AdaptiveHostConfig hostConfig, AdaptiveElementRenderers <HtmlTag, AdaptiveRenderContext> elementRenderers, Dictionary <string, object> elementDefinitions = default(Dictionary <string, object>)) { // clone it Config = JsonConvert.DeserializeObject <AdaptiveHostConfig>(JsonConvert.SerializeObject(hostConfig)); ElementRenderers = elementRenderers; ElementDefinitions = elementDefinitions; }
public static void InitializeRenderer(AdaptiveHostConfig hostConfig) { try { _renderer = new AdaptiveCardRenderer(); if (hostConfig != null) { _renderer.HostConfig = hostConfig; } if (Settings.UseFixedDimensions) { _renderer.SetFixedDimensions(320, 180); } // Custom resource resolvers _renderer.ResourceResolvers.Set("symbol", new MySymbolResourceResolver()); } catch { if (Debugger.IsAttached) { Debugger.Break(); } throw; } }
public MainPage() { this.InitializeComponent(); // Create a card renderer. _cardRendrer = new AdaptiveCardRenderer(); // Set several attributes on the renderer, including the font family and sizes. var hostConfig = new AdaptiveHostConfig { FontFamily = "Calibri", FontSizes = { Default = 20, Small = 15, Medium = 25, Large = 30, ExtraLarge = 40, } }; // Set the host config properties on the renderer. _cardRendrer.HostConfig = hostConfig; // Create the main card. CreateMainCard(); // Rendering the card enables the actions. RenderCard(_mainCard); }
public MainWindow() { InitializeComponent(); if (Dispatcher != null) { Dispatcher.UnhandledException += Dispatcher_UnhandledException; } CommandBinding cb = new CommandBinding(ApplicationCommands.Copy, this.CopyCmdExecuted, this.CopyCmdCanExecute); this.ConversationView.ConversationHistory.CommandBindings.Add(cb); this.ActivitiesPane.CommandBindings.Add(cb); this.ActivityPayloadPane.CommandBindings.Add(cb); this.DataContext = this; this.player.PlaybackStopped += this.Player_PlaybackStopped; Services.Tracker.Track(settings); Services.Tracker.Track(this); this.renderer = new AdaptiveCardRenderer(); this.renderer.UseXceedElementRenderers(); var configFile = Path.Combine(System.Reflection.Assembly.GetExecutingAssembly().Location, "AdaptiveCardsHostConfig.json"); if (File.Exists(configFile)) { this.renderer.HostConfig = AdaptiveHostConfig.FromJson(File.ReadAllText(configFile)); } }
public void MediaConfig() { // Default values var defaultHostConfig = AdaptiveHostConfig.FromJson(@"{}"); Assert.IsNotNull(defaultHostConfig); Assert.IsNotNull(defaultHostConfig.Media); Assert.IsNull(defaultHostConfig.Media.DefaultPoster); Assert.IsNull(defaultHostConfig.Media.PlayButton); Assert.AreEqual(true, defaultHostConfig.Media.AllowInlinePlayback); // Default values var hostConfig = AdaptiveHostConfig.FromJson(@"{ ""media"": { ""defaultPoster"": ""http://adaptivecards.io/content/media/poster.png"", ""playButton"": ""http://adaptivecards.io/content/media/playButton.png"", ""allowInlinePlayback"": false } }"); Assert.IsNotNull(hostConfig); Assert.IsNotNull(hostConfig.Media); Assert.AreEqual("http://adaptivecards.io/content/media/poster.png", hostConfig.Media.DefaultPoster); Assert.AreEqual("http://adaptivecards.io/content/media/playButton.png", hostConfig.Media.PlayButton); Assert.AreEqual(false, hostConfig.Media.AllowInlinePlayback); }
protected override void LoadPayload(string payload) { try { var newHostConfig = AdaptiveHostConfig.FromJsonString(payload).HostConfig; if (newHostConfig != null) { HostConfig = newHostConfig; HostConfigChanged?.Invoke(this, HostConfig); MakeErrorsLike(new List <ErrorViewModel>()); } else { SetSingleError(new ErrorViewModel() { Message = "Invalid Host Config payload", Type = ErrorViewModelType.ErrorButRenderAllowed }); } } catch (Exception ex) { Debug.WriteLine(ex.ToString()); SetSingleError(new ErrorViewModel() { Message = ex.ToString(), Type = ErrorViewModelType.ErrorButRenderAllowed }); } }
public AdaptiveCardMenuItem(AdaptiveHostConfig adaptiveHostConfig, IEventAggregator eventAggregator, IContextMenuTranslations contextMenuTranslations) { // automatically update the DisplayName contextMenuTranslations.CreateDisplayNameBinding(this, nameof(IContextMenuTranslations.ActiveCard)); Icon = new PackIconMaterial { Kind = PackIconMaterialKind.Cards }; ClickAction = clickedItem => { Log.Debug().WriteLine("ActiveCard"); var card = new AdaptiveCard("1.1") { Body = new List <AdaptiveElement> { new AdaptiveImage { HorizontalAlignment = AdaptiveHorizontalAlignment.Center, Size = AdaptiveImageSize.Large, Url = new Uri("http://static.nichtlustig.de/comics/full/150422.jpg") }, new AdaptiveImage { HorizontalAlignment = AdaptiveHorizontalAlignment.Center, Size = AdaptiveImageSize.Large, Url = new Uri("http://static.nichtlustig.de/comics/full/150421.jpg") } }, Actions = new List <AdaptiveAction> { new AdaptiveShowCardAction { Title = "Do you like this?", Card = new AdaptiveCard("1.1") { Body = new List <AdaptiveElement> { new AdaptiveTextInput { Id = "rating" } } } } } }; eventAggregator.PublishOnCurrentThread(new AdaptiveCardViewModel(adaptiveHostConfig, card, eventAggregator)); }; this.VisibleOnPermissions("Admin"); }
private void RenderAdaptiveCard(string cardJson, TimeSpan mediaPlayedPosition, string mediaUrl) { IsHitTestVisible = false; // Create a new adaptive card renderer. var renderer = new AdaptiveCardRenderer(); // Customize the font sizes via AdaptiveHostConfig. var hostConfig = new AdaptiveHostConfig { FontFamily = "Tw Cen MT", FontSizes = { Small = 14, Default = 16, Medium = 16, Large = 20, ExtraLarge = 24 } }; renderer.HostConfig = hostConfig; // Get card from json. var card = renderer.RenderAdaptiveCardFromJsonString(cardJson); // Attach the card content to UI. if (card.FrameworkElement is FrameworkElement element) { element.Loaded += (s, e) => { SetupExpressionAnimationsForCard(); var mediaElement = element.Children().OfType <MediaElement>().Single(); // TODO: Why mediaElement.Source is null here?? How do we // auto-play without hacking?? // If the following works, we don't have to pass in the mediaUrl // at all! Let me know if you know a better workaround. :) //mediaElement.Position = mediaPlayedPosition; //mediaElement.Play(); mediaElement.Source = new Uri(mediaUrl); mediaElement.MediaOpened += (o, a) => { mediaElement.Position = mediaPlayedPosition; //mediaElement.Play(); // This doesn't work... }; // Now the UI is ready. IsHitTestVisible = true; }; MediaContainer.Child = element; Card.Visibility = Visibility.Visible; } }
private void Update() { try { var renderer = new AdaptiveCardRenderer(AdaptiveHostConfig.FromJson(HostConfigs.CortanaHostConfig)); CardContainer.Child = renderer.RenderCard(AdaptiveCard.FromJson(TextBoxCard.Text).Card).FrameworkElement; } catch { } }
public async Task <ActionResult> Index(string cardUrl = null) { cardUrl = cardUrl ?? "https://raw.githubusercontent.com/Microsoft/AdaptiveCards/master/samples/v1.0/Scenarios/ActivityUpdate.json"; try { var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30)); // Get the JSON from the card URL var client = new HttpClient(); var response = await client.GetAsync(cardUrl, cts.Token); var json = await response.Content.ReadAsStringAsync(); // Make sure the payload has a version property var jObject = JObject.Parse(json); if (!jObject.TryGetValue("version", out var _)) { jObject["version"] = "0.5"; } // Parse the Adaptive Card JSON AdaptiveCardParseResult parseResult = AdaptiveCard.FromJson(jObject.ToString()); AdaptiveCard card = parseResult.Card; // Create a host config AdaptiveHostConfig hostConfig = new AdaptiveHostConfig() { SupportsInteractivity = false }; // TODO: Load custom host configs // Create a renderer AdaptiveCardRenderer renderer = new AdaptiveCardRenderer(hostConfig); // Set any XAML resource Dictionary if you have one renderer.ResourcesPath = System.IO.Path.Combine(_env.WebRootPath, "Styles", "MyStyles.xaml"); // Render the card to bitmap RenderedAdaptiveCardImage renderedCard = await renderer.RenderCardToImageAsync(card, createStaThread : true, cancellationToken : cts.Token); return(File(renderedCard.ImageStream, "image/png")); } catch (OperationCanceledException) { // Timed out return(StatusCode((int)HttpStatusCode.RequestTimeout)); } catch (Exception) { // TODO: log throw; } }
protected override AdaptiveCardRenderer CreateObject(string str) { var hostConfig = AdaptiveHostConfig.FromJsonString(str).HostConfig; return(new AdaptiveCardRenderer() { HostConfig = hostConfig }); }
public void ContainerStyleForegroundColors() { var hostConfig = new AdaptiveHostConfig(); hostConfig.ContainerStyles.Emphasis.ForegroundColors = new ForegroundColorsConfig() { Default = new FontColorConfig("#FFcc3300") }; var card = new AdaptiveCard("1.2") { Body = new System.Collections.Generic.List <AdaptiveElement>() { new AdaptiveContainer() { Style = AdaptiveContainerStyle.Emphasis, Items = new System.Collections.Generic.List <AdaptiveElement>() { new AdaptiveTextBlock() { Text = "container 1 -- emphasis style text" }, new AdaptiveContainer() { Style = AdaptiveContainerStyle.Accent, Items = new System.Collections.Generic.List <AdaptiveElement>() { new AdaptiveTextBlock() { Text = "container 1.1 -- accent style text" } } }, new AdaptiveTextBlock() { Text = "container 1 -- emphasis style text" } } }, new AdaptiveTextBlock() { Text = "default style text" } } }; var renderer = new AdaptiveCardRenderer(hostConfig); var result = renderer.RenderCard(card); var generatedHtml = result.Html.ToString(); var randomGeneratedIds = FindAllRandomGeneratedIds(generatedHtml); Assert.AreEqual( "<div class='ac-adaptivecard' style='width: 100%;background-color: rgba(255, 255, 255, 1.00);padding: 15px;box-sizing: border-box;justify-content: flex-start;'><div class='ac-container' style='padding-right: 15px;padding-left: 15px;padding-top: 15px;padding-bottom: 15px;background-color: rgba(0, 0, 0, 0.03);justify-content: flex-start;'><div class='ac-textblock' style='box-sizing: border-box;text-align: left;color: rgba(204, 51, 0, 1.00);line-height: 18.62px;font-size: 14px;font-weight: 400;white-space: nowrap;'><p style='margin-top: 0px;margin-bottom: 0px;width: 100%;text-overflow: ellipsis;overflow: hidden;'>container 1 -- emphasis style text</p></div><div class='ac-separator' id='" + randomGeneratedIds[0] + "' style='height: 8px;'></div><div class='ac-container' data-ac-separatorId='" + randomGeneratedIds[0] + "' style='padding-right: 15px;padding-left: 15px;padding-top: 15px;padding-bottom: 15px;background-color: #dce5f7;justify-content: flex-start;'><div class='ac-textblock' style='box-sizing: border-box;text-align: left;color: rgba(0, 0, 0, 1.00);line-height: 18.62px;font-size: 14px;font-weight: 400;white-space: nowrap;'><p style='margin-top: 0px;margin-bottom: 0px;width: 100%;text-overflow: ellipsis;overflow: hidden;'>container 1.1 -- accent style text</p></div></div><div class='ac-separator' id='" + randomGeneratedIds[1] + "' style='height: 8px;'></div><div class='ac-textblock' data-ac-separatorId='" + randomGeneratedIds[1] + "' style='box-sizing: border-box;text-align: left;color: rgba(204, 51, 0, 1.00);line-height: 18.62px;font-size: 14px;font-weight: 400;white-space: nowrap;'><p style='margin-top: 0px;margin-bottom: 0px;width: 100%;text-overflow: ellipsis;overflow: hidden;'>container 1 -- emphasis style text</p></div></div><div class='ac-separator' id='" + randomGeneratedIds[2] + "' style='height: 8px;'></div><div class='ac-textblock' data-ac-separatorId='" + randomGeneratedIds[2] + "' style='box-sizing: border-box;text-align: left;color: rgba(0, 0, 0, 1.00);line-height: 18.62px;font-size: 14px;font-weight: 400;white-space: nowrap;'><p style='margin-top: 0px;margin-bottom: 0px;width: 100%;text-overflow: ellipsis;overflow: hidden;'>default style text</p></div></div>", generatedHtml); }
public DiscordMapper(DiscordMapperOptions options) { _options = options; // Create a host config with no interactivity // (buttons in images would be deceiving) _adaptiveHostConfig = new AdaptiveHostConfig() { SupportsInteractivity = false }; }
private AdaptiveHostConfig LoadHostConfig() { Assembly assembly = typeof(AdaptiveCardView).Assembly; using (Stream stream = assembly.GetManifestResourceStream("Blastic.Themes.AdaptiveCardConfig.json")) using (StreamReader reader = new StreamReader(stream)) { return(AdaptiveHostConfig.FromJson(reader.ReadToEnd())); } }
public static async Task Main(string[] args) { configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetParent(AppContext.BaseDirectory).FullName) .AddJsonFile("appsettings.json", false) .AddJsonFile("appsettings.local.json", true) .Build(); var templateJson = File.ReadAllText("Template1.json", Encoding.UTF8); var data = new { tenantname = "Stavanger", categoryname = "Avløp", statusname = "Under prosessering", deadline = "2020-02-07T09:20:00Z", taskurl = "https://melding.powel.net/stavanger/tasks/some-random-id" }; var dataJson = JsonConvert.SerializeObject(data); var transformer = new AdaptiveCards.Templating.AdaptiveTransformer(); var transformed = transformer.Transform(templateJson, dataJson); var hostConfig = new AdaptiveHostConfig { SupportsInteractivity = true }; var renderer = new AdaptiveCardRenderer(hostConfig); // make link html simpler - Outlook is not good at rendering html! renderer.ElementRenderers.Remove <AdaptiveOpenUrlAction>(); renderer.ElementRenderers.Set <AdaptiveOpenUrlAction>((action, context) => { var aTag = new HtmlTag("a").AddClass("ac-action-openUrl"); aTag.Attributes.Add("href", action.Url.ToString()); aTag.Text = action.Title; return(aTag); }); var parsedCard = AdaptiveCard.FromJson(transformed); parsedCard.Card.Lang = "nb-no"; // set to whatever language makes more sense var renderedCard = renderer.RenderCard(parsedCard.Card); var htmlContent = renderedCard.Html.ToString(); var from = new EmailAddress("*****@*****.**", "Ikke svar"); var subject = "Ny oppgave fra Powel Melding"; var to = new EmailAddress("*****@*****.**", "Jarle Nygård"); var msg = MailHelper.CreateSingleEmail(from, to, subject, string.Empty, htmlContent); var client = new SendGridClient(configuration["SendgridApiKey"]); var response = await client.SendEmailAsync(msg); }
/// <summary> /// 3. Use AdaptiveCardRenderer to create a UWP UI element from a JSON payload. /// </summary> private async Task RenderCardsAsync() { // Create a new adaptive card renderer. var renderer = new AdaptiveCardRenderer(); // Customize the font sizes via AdaptiveHostConfig. var hostConfig = new AdaptiveHostConfig { FontSizes = { Small = 14, Default = 16, Medium = 16, Large = 20, ExtraLarge = 24 } }; renderer.HostConfig = hostConfig; // Get our JSON string from a .json file. var json1 = File.ReadAllText(Package.Current.InstalledLocation.Path + @"\AdaptiveCards\bot1.json"); var json2 = File.ReadAllText(Package.Current.InstalledLocation.Path + @"\AdaptiveCards\bot2.json"); var json3 = File.ReadAllText(Package.Current.InstalledLocation.Path + @"\AdaptiveCards\bot3.json"); // Parse the JSON string to AdaptiveCardParseResult. var card1 = AdaptiveCard.FromJsonString(json1); var card2 = AdaptiveCard.FromJsonString(json2); var card3 = AdaptiveCard.FromJsonString(json3); await RenderCardElementAsync(renderer, card1); await AddProgressIndicatorAsync("\"Closest first\""); await Task.Delay(1000); await RenderCardElementAsync(renderer, card2); await AddProgressIndicatorAsync("\"Team selected\""); await Task.Delay(1000); await RenderCardElementAsync(renderer, card3); AdjustersFoundText.Text = "Adjuster found!"; DimUnavailableAdjusters(); await AddProgressIndicatorAsync("\"Notification sent!\"", true); await Task.Delay(3000); VisualStateManager.GoToState(this, "EmptyState", true); }
public MainWindow() { InitializeComponent(); webBrowser.SuppressScriptErrors(true); _hostconfig = new AdaptiveHostConfig { Actions = { ShowCard = { ActionMode = ShowCardActionMode.Popup } } }; }
/// <inheritdoc /> protected override void Load(ContainerBuilder builder) { // Create a default AdaptiveHostConfig if no other is specified builder.Register(context => { var resourceProvider = context.Resolve <IResourceProvider>(); var resources = resourceProvider.GetCachedManifestResourceNames(ThisAssembly); using var stream = resourceProvider.LocateResourceAsStream(ThisAssembly, @"HostConfigs\Windows10Toast.json"); using var streamReader = new StreamReader(stream); return(AdaptiveHostConfig.FromJson(streamReader.ReadToEnd())); }) .IfNotRegistered(typeof(AdaptiveHostConfig)) .As <AdaptiveHostConfig>() .SingleInstance(); }
private void RenderAdaptiveCard() { // We want to make sure _mediaElement and _cardJson are populated before any interaction to the UI. IsHitTestVisible = false; // Create a new adaptive card renderer. var renderer = new AdaptiveCardRenderer(); // Customize the font sizes via AdaptiveHostConfig. var hostConfig = new AdaptiveHostConfig { FontFamily = "Tw Cen MT", FontSizes = { Small = 14, Default = 16, Medium = 16, Large = 20, ExtraLarge = 24 } }; renderer.HostConfig = hostConfig; // Get card from json. _cardJson = CreateMediaAdaptiveCardJson(); var card = renderer.RenderAdaptiveCardFromJsonString(_cardJson); // Monitor when video is played... // TODO: Not fired... Bug??? card.MediaClicked += (c, e) => { }; // Attach the card content to UI. if (card.FrameworkElement is FrameworkElement element) { element.Loaded += (s, e) => { _mediaElement = element.Children().OfType <MediaElement>().Single(); // Now the UI is ready. IsHitTestVisible = true; SetupInteractionTracker(); }; MediaContainer.Child = element; } }
private async void TriggerUpdate() { if (_isUpdating) { return; } _isUpdating = true; try { if (_renderer == null) { _renderer = new AdaptiveCardRenderer(); _renderer.SetFixedDimensions(320, 176); var hostConfigsFolder = await Package.Current.InstalledLocation.GetFolderAsync("HostConfigs"); var hostConfigFile = await hostConfigsFolder.GetFileAsync("TimelineWindows.json"); _renderer.HostConfig = AdaptiveHostConfig.FromJsonString(await FileIO.ReadTextAsync(hostConfigFile)).HostConfig; } if (CardPayload == null) { RenderedElement = null; RenderedSuccessfully = false; } else { var renderResult = _renderer.RenderAdaptiveCardFromJsonString(CardPayload.ToString()); RenderedElement = renderResult.FrameworkElement; RenderedSuccessfully = RenderedElement != null; } } catch { RenderedElement = null; RenderedSuccessfully = false; } finally { _isUpdating = false; } }
protected override void LoadPayload(string payload) { try { HostConfig = AdaptiveHostConfig.CreateHostConfigFromJson(payload); HostConfigChanged?.Invoke(this, HostConfig); } catch (Exception ex) { Debug.WriteLine(ex.ToString()); SetSingleError(new ErrorViewModel() { Message = "Invalid Host Config payload", Type = ErrorViewModelType.ErrorButRenderAllowed }); } }
private async static Task RenderAdaptiveCard(Attachment attachment) { // This is entirely optional, just shows how to render an adaptive card which in a console app isn't really very practical! try { AdaptiveCardParseResult result = AdaptiveCard.FromJson(attachment.Content.ToString()); var adaptiveCard = AdaptiveCard.FromJson(attachment.Content.ToString()); if (adaptiveCard != null) { // Create a host config with no interactivity // (buttons in images would be deceiving) AdaptiveHostConfig hostConfig = new AdaptiveHostConfig() { SupportsInteractivity = false }; // Create a renderer AdaptiveCardRenderer renderer = new AdaptiveCardRenderer(hostConfig); // Render the card to png RenderedAdaptiveCardImage renderedCard = await renderer.RenderCardToImageAsync(adaptiveCard.Card, createStaThread : true, cancellationToken : default(CancellationToken)); string fileName = $"{Guid.NewGuid()}.png"; using (var fileStream = File.Create(fileName)) { renderedCard.ImageStream.Seek(0, SeekOrigin.Begin); renderedCard.ImageStream.CopyTo(fileStream); } Console.WriteLine($"Adaptive Card rendered to {fileName} for debug purposes."); Process.Start(fileName); } Console.WriteLine($"Adaptive Card Speak Property: {adaptiveCard.Card.Speak}"); } catch (Exception) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Adaptive card not parsed"); Console.ForegroundColor = ConsoleColor.Gray; } }
public static void InitializeRenderer(AdaptiveHostConfig hostConfig) { try { _renderer = new AdaptiveCardRenderer(); if (hostConfig != null) { _renderer.HostConfig = hostConfig; } if (Settings.UseFixedDimensions) { _renderer.SetFixedDimensions(320, 180); } // Custom resource resolvers _renderer.ResourceResolvers.Set("symbol", new MySymbolResourceResolver()); /* * Example on how to override the Action Positive and Destructive styles * Style positiveStyle = new Style(typeof(Button)); * positiveStyle.Setters.Add(new Setter(Button.BackgroundProperty, new SolidColorBrush(Windows.UI.Colors.LawnGreen))); * Style destructiveStyle = new Style(typeof(Button)); * destructiveStyle.Setters.Add(new Setter(Button.BackgroundProperty, new SolidColorBrush(Windows.UI.Colors.Red))); * Style otherStyle = new Style(typeof(Button)); * otherStyle.Setters.Add(new Setter(Button.BackgroundProperty, new SolidColorBrush(Windows.UI.Colors.Yellow))); * otherStyle.Setters.Add(new Setter(Button.ForegroundProperty, new SolidColorBrush(Windows.UI.Colors.DarkRed))); * * _renderer.OverrideStyles = new ResourceDictionary(); * _renderer.OverrideStyles.Add("Adaptive.Action.Positive", positiveStyle); * _renderer.OverrideStyles.Add("Adaptive.Action.Destructive", destructiveStyle); * _renderer.OverrideStyles.Add("Adaptive.Action.other", otherStyle); */ } catch { if (Debugger.IsAttached) { Debugger.Break(); } throw; } }
public void TestParsingHostConfig() { var result = AdaptiveHostConfig.FromJson(@"{ ""fontSizes"": { ""small"": 25, ""default"": 26, ""medium"": 27, ""large"": 28, ""extraLarge"": 29 } }"); Assert.IsNotNull(result); Assert.AreEqual(25, result.FontSizes.Small); Assert.AreEqual(26, result.FontSizes.Default); Assert.AreEqual(27, result.FontSizes.Medium); Assert.AreEqual(28, result.FontSizes.Large); Assert.AreEqual(29, result.FontSizes.ExtraLarge); }
public static void InitializeRenderer(AdaptiveHostConfig hostConfig) { try { _renderer = new XamlCardRenderer(); if (hostConfig != null) { _renderer.SetHostConfig(hostConfig); } // Custom resource resolvers _renderer.ResourceResolvers.Set("symbol", new MySymbolResourceResolver()); _renderer.Action += async(sender, e) => { var m_actionDialog = new ContentDialog(); if (e.Action.ActionType == ActionType.ShowCard) { AdaptiveShowCardAction showCardAction = (AdaptiveShowCardAction)e.Action; m_actionDialog.Content = await _renderer.RenderCardAsXamlAsync(showCardAction.Card); } else { m_actionDialog.Content = "We got an action!\n" + e.Action.ActionType + "\n" + e.Inputs; } m_actionDialog.PrimaryButtonText = "Close"; await m_actionDialog.ShowAsync(); }; } catch { if (Debugger.IsAttached) { Debugger.Break(); } throw; } }