예제 #1
0
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            var adaptiveCard = (AdaptiveCards.AdaptiveCard)value;
            var renderedCard = _renderer.RenderAdaptiveCard(AdaptiveCard.FromJsonString(adaptiveCard.ToJson()).AdaptiveCard);

            return(renderedCard.FrameworkElement);
        }
예제 #2
0
        public async Task RenderInDispatcher(AdaptiveCard card)
        {
            RenderedAdaptiveCard renderedCard = null;

            // Need to move the test to the UI Thread to render the card
            var       dispatcher          = CoreApplication.MainView.CoreWindow.Dispatcher;
            Exception dispatcherException = null;
            await dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
            {
                try
                {
                    var renderer = new AdaptiveCardRenderer();

                    renderedCard = renderer.RenderAdaptiveCard(card);
                }
                catch (Exception e)
                {
                    // If we throw an exception from inside the dispatcher the test infrastructure loses its
                    // connection with the tests. Hold onto this and throw it from the main test thread so
                    // it is reported properly as a test failure.
                    dispatcherException = e;
                }
            });

            if (dispatcherException != null)
            {
                // Rethrow any exceptions that may have happened within the dispatcher
                throw dispatcherException;
            }

            Assert.AreEqual(0, renderedCard.Warnings.Count);
            Assert.AreEqual(0, renderedCard.Errors.Count);
        }
        public async Task ActionRendererRegistraton_CustomActionTest()
        {
            var dispatcher = CoreApplication.MainView.CoreWindow.Dispatcher;

            // Need to move the test to the UI Thread
            await dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
            {
                AdaptiveActionParserRegistration actionParserRegistration = new AdaptiveActionParserRegistration();
                List <AdaptiveWarning> warnings = new List <AdaptiveWarning>();

                actionParserRegistration.Set("TestCustomAction", new TestActionParser());

                String testCard =
                    "{" +
                    "   \"type\":\"AdaptiveCard\"," +
                    "   \"version\":\"1.0\"," +
                    "   \"body\":" +
                    "   [" +
                    "   ]," +
                    "   \"actions\":" +
                    "   [" +
                    "       {" +
                    "           \"type\":\"TestCustomAction\"" +
                    "       }," +
                    "       {" +
                    "           \"type\":\"Action.Submit\"" +
                    "       }" +
                    "   ]" +
                    "}";

                AdaptiveCard card = AdaptiveCard.FromJsonString(testCard, null, actionParserRegistration).AdaptiveCard;
                Assert.IsNotNull(card);

                AdaptiveCardRenderer renderer = new AdaptiveCardRenderer();

                renderer.ActionRenderers.Set("TestCustomAction", new TestCustomActionRenderer());
                renderer.ActionRenderers.Set("Action.Submit", new TestSubmitActionRenderer());

                Assert.IsNotNull(renderer.ActionRenderers.Get("TestCustomAction") as TestCustomActionRenderer);
                Assert.IsNotNull(renderer.ActionRenderers.Get("Action.Submit") as TestSubmitActionRenderer);

                FrameworkElement renderedCard = renderer.RenderAdaptiveCard(card).FrameworkElement;

                bool submitFound = false;
                bool customFound = false;
                foreach (var radioButton in RenderTestHelpers.GetAllDescendants(renderedCard).OfType <RadioButton>())
                {
                    customFound |= radioButton.Name == "CustomActionRadioButton";
                    submitFound |= radioButton.Name == "SubmitActionRadioButton";
                }

                Assert.IsTrue(customFound && submitFound);

                renderer.ActionRenderers.Remove("TestCustomAction");
                renderer.ActionRenderers.Remove("Action.Submit");
                renderer.ActionRenderers.Remove("TestCustomActionThatDoesntExist");
            });
        }
예제 #4
0
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            if (_renderer == null)
            {
                _renderer = new AdaptiveCardRenderer();
            }

            var json = ((AppContent)value).ToAdaptiveCard().ToJson();

            return(_renderer.RenderAdaptiveCard(AdaptiveCard.FromJsonString(json).AdaptiveCard).FrameworkElement);
        }
예제 #5
0
 private FrameworkElement Render(Cards.AdaptiveCard card, out string json)
 {
     try
     {
         RenderedAdaptiveCard rendered = renderer.RenderAdaptiveCard(Convert(card, out json));
         return(rendered.FrameworkElement);
     }
     catch (Exception)
     {
         json = null;
         return(null);
     }
 }
예제 #6
0
        private async void OnNewTodo(object sender, RoutedEventArgs e)
        {
            AdaptiveCardRenderer renderer = new AdaptiveCardRenderer();

            string json = new JsonCreator().CreateJson(TodoTitle.Text);
            AdaptiveCardParseResult card = AdaptiveCard.FromJson(json);
            var renderResult             = renderer.RenderAdaptiveCard(card.Card);

            if (renderResult != null)
            {
                MainPanel.Children.Add(renderResult.FrameworkElement);
            }
        }
        private void RenderAdaptiveCard(string jsonString)
        {
            var renderer = new AdaptiveCardRenderer();
            var card     = AdaptiveCard.FromJsonString(jsonString);
            RenderedAdaptiveCard renderedAdaptiveCard = renderer.RenderAdaptiveCard(card.AdaptiveCard);

            if (renderedAdaptiveCard.FrameworkElement != null)
            {
                // Get the framework element
                var uiCard = renderedAdaptiveCard.FrameworkElement;

                // Add it to your UI
                cardsGrid.Children.Add(uiCard);
            }
        }
예제 #8
0
        private async void OnShowCard(object sender, RoutedEventArgs e)
        {
            async Task ShowSubmitActionAsync(RenderedAdaptiveCard card, AdaptiveSubmitAction action)
            {
                var    inputs = card.UserInputs.AsJson();
                string text   = $"{inputs} {action.ToJson()}";

                await new MessageDialog(text).ShowAsync();
            }

            void OpenUrlAction(RenderedAdaptiveCard card, AdaptiveOpenUrlAction action)
            {
                webView.Navigate(action.Url);
            }

            AdaptiveCardRenderer renderer = new AdaptiveCardRenderer();

            renderer.HostConfig = _hostConfig;

            var result       = AdaptiveCard.FromJsonString(await LoadJsonAsync());
            var renderedCard = renderer.RenderAdaptiveCard(result.AdaptiveCard);

            renderedCard.Action += async(RenderedAdaptiveCard card, AdaptiveActionEventArgs args) =>
            {
                switch (args.Action)
                {
                case AdaptiveSubmitAction submitAction:
                    await ShowSubmitActionAsync(card, submitAction);

                    break;

                case AdaptiveShowCardAction showCardAction:
                    // nothing to do if the activity is shown inline
                    break;

                case AdaptiveOpenUrlAction openUrlAction:
                    OpenUrlAction(card, openUrlAction);
                    break;

                default:
                    break;
                }
            };
            grid1.Children.Clear();
            grid1.Children.Add(renderedCard.FrameworkElement);
        }
예제 #9
0
        private Task RenderCardElementAsync(AdaptiveCardRenderer renderer, AdaptiveCardParseResult card)
        {
            var taskSource = new TaskCompletionSource <bool>();

            // Get the RenderedAdaptiveCard from the parse result.
            var renderResult = renderer.RenderAdaptiveCard(card.AdaptiveCard);

            renderResult.Action += OnRenderResultAction;

            // Add the AdaptiveCard UIElement to the Visual Tree.
            if (renderResult.FrameworkElement is FrameworkElement cardElement)
            {
                cardElement.Loaded    += OnCardElementLoaded;
                cardElement.Visibility = Visibility.Collapsed;
                cardElement.Margin     = new Thickness(12, 0, 12, 0);

                Implicit.SetAnimations(cardElement, OffsetImplicitAnimations);
                Implicit.SetShowAnimations(cardElement, CardElementShowAnimations);
                Implicit.SetHideAnimations(cardElement, CardElementHideAnimations);

                CardsPanel.Children.Add(cardElement);
            }

            void OnCardElementLoaded(object sender, RoutedEventArgs e)
            {
                cardElement.Loaded -= OnCardElementLoaded;

                cardElement.Visibility = Visibility.Visible;
            }

            async void OnRenderResultAction(RenderedAdaptiveCard sender, AdaptiveActionEventArgs args)
            {
                renderResult.Action -= OnRenderResultAction;

                if (args.Action.ActionType == ActionType.Submit)
                {
                    sender.FrameworkElement.Visibility = Visibility.Collapsed;
                    await Task.Delay(600);

                    taskSource.TrySetResult(true);
                }
            }

            return(taskSource.Task);
        }
예제 #10
0
        public UIElement Render(IAdaptiveCardElement element, AdaptiveRenderContext context, AdaptiveRenderArgs renderArgs)
        {
            var card = new AdaptiveCard();

            foreach (var a in (element as AdaptiveActionSet).Actions)
            {
                card.Actions.Add(a);
            }

            var originalPadding = m_cardRenderer.HostConfig.Spacing.Padding;

            m_cardRenderer.HostConfig.Spacing.Padding = 0;
            var result = m_cardRenderer.RenderAdaptiveCard(card).FrameworkElement;

            m_cardRenderer.HostConfig.Spacing.Padding = originalPadding;

            return(result);
        }
예제 #11
0
        private async void OnRenderAdaptiveCard(object sender, RoutedEventArgs e)
        {
            HttpClient client = new HttpClient();

            json = await client.GetStringAsync(new Uri("https://adaptivecard.azurewebsites.net/api/AppConsultAdaptiveCards?code=AzSEpdNE/P0c9OFIBjro2vSKwGIlLdBWdc53/jmR7Y9PX2l1Ks0/nQ=="));

            AdaptiveCardParseResult card = AdaptiveCard.FromJsonString(json);

            AdaptiveCardRenderer renderer = new AdaptiveCardRenderer();
            var renderResult = renderer.RenderAdaptiveCard(card.AdaptiveCard);

            renderResult.Action += RenderResult_OnAction;

            if (renderResult != null)
            {
                MainPanel.Children.Add(renderResult.FrameworkElement);
            }
        }
예제 #12
0
        protected override async void LoadPayload(string payload)
        {
            var newErrors = await PayloadValidator.ValidateAsync(payload);

            if (newErrors.Any(i => i.Type == ErrorViewModelType.Error))
            {
                MakeErrorsLike(newErrors);
                return;
            }

            try
            {
                if (_renderer == null)
                {
                    InitializeRenderer(MainPageViewModel.HostConfigEditor.HostConfig);
                }
            }
            catch (Exception ex)
            {
                newErrors.Add(new ErrorViewModel()
                {
                    Message = "Initializing renderer error: " + ex.ToString(),
                    Type    = ErrorViewModelType.Error
                });
                MakeErrorsLike(newErrors);
                return;
            }

            try
            {
                JsonObject jsonObject;
                if (JsonObject.TryParse(payload, out jsonObject))
                {
                    RenderedAdaptiveCard renderResult = _renderer.RenderAdaptiveCardFromJson(jsonObject);
                    if (renderResult.FrameworkElement != null)
                    {
                        RenderedCard         = renderResult.FrameworkElement;
                        renderResult.Action += async(sender, e) =>
                        {
                            var m_actionDialog = new ContentDialog();

                            if (e.Action.ActionType == ActionType.ShowCard)
                            {
                                AdaptiveShowCardAction showCardAction   = (AdaptiveShowCardAction)e.Action;
                                RenderedAdaptiveCard   renderedShowCard = _renderer.RenderAdaptiveCard(showCardAction.Card);
                                if (renderedShowCard.FrameworkElement != null)
                                {
                                    m_actionDialog.Content = renderedShowCard.FrameworkElement;
                                }
                            }
                            else
                            {
                                m_actionDialog.Content = SerializeActionEventArgsToString(e);
                            }

                            m_actionDialog.PrimaryButtonText = "Close";

                            await m_actionDialog.ShowAsync();
                        };
                    }
                    else
                    {
                        newErrors.Add(new ErrorViewModel()
                        {
                            Message = "There was an error Rendering this card",
                            Type    = ErrorViewModelType.Error
                        });
                    }
                }
                else
                {
                    newErrors.Add(new ErrorViewModel()
                    {
                        Message = "There was an error creating a JsonObject from the card",
                        Type    = ErrorViewModelType.Error
                    });
                }

                if (RenderedCard is FrameworkElement)
                {
                    (RenderedCard as FrameworkElement).VerticalAlignment = VerticalAlignment.Top;
                }
                MakeErrorsLike(newErrors);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
                newErrors.Add(new ErrorViewModel()
                {
                    Message = "Rendering failed",
                    Type    = ErrorViewModelType.Error
                });
                MakeErrorsLike(newErrors);
            }
        }
예제 #13
0
        protected override async void LoadPayload(string payload)
        {
            var newErrors = await PayloadValidator.ValidateAsync(payload);

            if (newErrors.Any(i => i.Type == ErrorViewModelType.Error))
            {
                MakeErrorsLike(newErrors);
                return;
            }

            try
            {
                if (_renderer == null)
                {
                    InitializeRenderer(MainPageViewModel.HostConfigEditor.HostConfig);
                }
            }
            catch (Exception ex)
            {
                newErrors.Add(new ErrorViewModel()
                {
                    Message = "Initializing renderer error: " + ex.ToString(),
                    Type    = ErrorViewModelType.Error
                });
                MakeErrorsLike(newErrors);
                return;
            }

            try
            {
                JsonObject jsonObject;
                if (JsonObject.TryParse(payload, out jsonObject))
                {
                    AdaptiveCardParseResult parseResult = AdaptiveCard.FromJson(jsonObject);

                    RenderedAdaptiveCard renderResult = _renderer.RenderAdaptiveCard(parseResult.AdaptiveCard);
                    if (renderResult.FrameworkElement != null)
                    {
                        RenderedCard         = renderResult.FrameworkElement;
                        renderResult.Action += async(sender, e) =>
                        {
                            var m_actionDialog = new ContentDialog();

                            if (e.Action.ActionType == ActionType.ShowCard)
                            {
                                AdaptiveShowCardAction showCardAction   = (AdaptiveShowCardAction)e.Action;
                                RenderedAdaptiveCard   renderedShowCard = _renderer.RenderAdaptiveCard(showCardAction.Card);
                                if (renderedShowCard.FrameworkElement != null)
                                {
                                    m_actionDialog.Content = renderedShowCard.FrameworkElement;
                                }
                            }
                            else
                            {
                                m_actionDialog.Content = SerializeActionEventArgsToString(e);
                            }

                            m_actionDialog.PrimaryButtonText = "Close";

                            await m_actionDialog.ShowAsync();
                        };

                        if (!MainPageViewModel.HostConfigEditor.HostConfig.Media.AllowInlinePlayback)
                        {
                            renderResult.MediaPlay += async(sender, e) =>
                            {
                                var onPlayDialog = new ContentDialog();
                                onPlayDialog.Content = "MediaPlayEvent:";

                                foreach (var source in e.Media.Sources)
                                {
                                    onPlayDialog.Content += "\n" + source.Url + " (" + source.MimeType + ")";
                                }

                                onPlayDialog.PrimaryButtonText = "Close";

                                await onPlayDialog.ShowAsync();
                            };
                        }
                        else
                        {
                            renderResult.MediaEnded += async(sender, e) =>
                            {
                                var mediaEndedDialog = new ContentDialog();
                                mediaEndedDialog.Content = "Media Ended Event:";

                                foreach (var source in e.Media.Sources)
                                {
                                    mediaEndedDialog.Content += "\n" + source.Url + " (" + source.MimeType + ")";
                                }

                                mediaEndedDialog.PrimaryButtonText = "Close";

                                await mediaEndedDialog.ShowAsync();
                            };
                        }
                    }
                    else
                    {
                        newErrors.Add(new ErrorViewModel()
                        {
                            Message = "There was an error Rendering this card",
                            Type    = ErrorViewModelType.Error
                        });
                    }
                    foreach (var error in parseResult.Errors)
                    {
                        newErrors.Add(new ErrorViewModel()
                        {
                            Message = error.Message,
                            Type    = ErrorViewModelType.Error
                        });
                    }
                    foreach (var error in renderResult.Errors)
                    {
                        newErrors.Add(new ErrorViewModel()
                        {
                            Message = error.Message,
                            Type    = ErrorViewModelType.Error
                        });
                    }
                    foreach (var error in parseResult.Warnings)
                    {
                        newErrors.Add(new ErrorViewModel()
                        {
                            Message = error.Message,
                            Type    = ErrorViewModelType.Warning
                        });
                    }

                    foreach (var error in renderResult.Warnings)
                    {
                        newErrors.Add(new ErrorViewModel()
                        {
                            Message = error.Message,
                            Type    = ErrorViewModelType.Warning
                        });
                    }
                }
                else
                {
                    newErrors.Add(new ErrorViewModel()
                    {
                        Message = "There was an error creating a JsonObject from the card",
                        Type    = ErrorViewModelType.Error
                    });
                }

                if (RenderedCard is FrameworkElement)
                {
                    (RenderedCard as FrameworkElement).VerticalAlignment = VerticalAlignment.Top;
                }
                MakeErrorsLike(newErrors);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
                newErrors.Add(new ErrorViewModel()
                {
                    Message = "Rendering failed",
                    Type    = ErrorViewModelType.Error
                });
                MakeErrorsLike(newErrors);
            }
        }
예제 #14
0
        public static async Task <Tuple <string, string, UIElement, double> > RenderCard(FileViewModel cardFile, FileViewModel hostConfigFile)
        {
            string           error = null;
            string           roundTrippedJsonString = null;
            FrameworkElement xaml      = null;
            double           cardWidth = 400;

            try
            {
                AdaptiveHostConfig hostConfig = AdaptiveHostConfig.FromJsonString(hostConfigFile.Contents).HostConfig;

                if (hostConfig == null)
                {
                    error = "Parsing hostConfig failed";
                }

                else
                {
                    AdaptiveCard card = AdaptiveCard.FromJsonString(cardFile.Contents).AdaptiveCard;

                    if (card == null)
                    {
                        error = "Parsing card failed";
                    }

                    else
                    {
                        roundTrippedJsonString = card.ToJson().ToString();
                        card = AdaptiveCard.FromJsonString(roundTrippedJsonString).AdaptiveCard;

                        var renderer = new AdaptiveCardRenderer()
                        {
                            HostConfig = hostConfig
                        };

                        if (hostConfigFile.Name.Contains("windows-timeline"))
                        {
                            renderer.SetFixedDimensions(320, 180);
                            cardWidth = 320;
                        }
                        else if (hostConfigFile.Name.Contains("windows-live-tile"))
                        {
                            renderer.SetFixedDimensions(310, 310);
                            cardWidth = 310;
                        }

                        xaml = renderer.RenderAdaptiveCard(card).FrameworkElement as FrameworkElement;

                        if (xaml == null)
                        {
                            error = "Rendering card failed";
                        }

                        else
                        {
                            xaml = new Border()
                            {
                                Background       = new SolidColorBrush(Colors.White),
                                Child            = xaml,
                                IsHitTestVisible = false // Disable HitTest so that mouse pointer can't accidently hover over a button
                            };

                            // The theme is important to set since it'll ensure buttons/inputs appear correctly
                            if (hostConfigFile.Name.Contains("windows-notification"))
                            {
                                xaml.RequestedTheme = ElementTheme.Dark;
                            }
                            else
                            {
                                xaml.RequestedTheme = ElementTheme.Light;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                error = ex.ToString();
            }

            return(new Tuple <string, string, UIElement, double>(error, roundTrippedJsonString, xaml, cardWidth));
        }
예제 #15
0
        public async Task RequiresAdaptiveCardsTest()
        {
            AdaptiveCard      card       = new AdaptiveCard();
            AdaptiveTextBlock textBlock1 = new AdaptiveTextBlock
            {
                Text = "Text Block 1 requires adaptive cards 5 and has fallback content."
            };

            AdaptiveTextBlock fallbackTextBlock = new AdaptiveTextBlock
            {
                Text = "Text Block 1 falls back to this."
            };

            textBlock1.FallbackContent = fallbackTextBlock;
            textBlock1.Requirements.Add(new AdaptiveRequirement("adaptiveCards", "5.0"));

            Assert.AreEqual(FallbackType.Content, textBlock1.FallbackType);

            card.Body.Add(textBlock1);

            AdaptiveTextBlock textBlock2 = new AdaptiveTextBlock
            {
                Text = "Text Block 2 requires adaptive cards 5 and is dropped."
            };

            textBlock2.FallbackType = FallbackType.Drop;
            textBlock2.Requirements.Add(new AdaptiveRequirement("adaptiveCards", "5.0"));

            Assert.AreEqual(FallbackType.Drop, textBlock2.FallbackType);

            card.Body.Add(textBlock2);

            AdaptiveTextBlock textBlock3 = new AdaptiveTextBlock
            {
                Text = "Text Block 3 requires adaptive cards 5 and has no specified fallback."
            };

            textBlock3.Requirements.Add(new AdaptiveRequirement("adaptiveCards", "5.0"));

            Assert.AreEqual(FallbackType.None, textBlock3.FallbackType);

            card.Body.Add(textBlock3);

            AdaptiveTextBlock textBlock4 = new AdaptiveTextBlock
            {
                Text = "Text Block 4 requires adaptive cards 1."
            };

            textBlock4.Requirements.Add(new AdaptiveRequirement("adaptiveCards", "1.0"));

            Assert.AreEqual(FallbackType.None, textBlock4.FallbackType);

            card.Body.Add(textBlock4);

            AdaptiveTextBlock textBlock5 = new AdaptiveTextBlock
            {
                Text = "Text Block 5 requires any version of adaptive cards."
            };

            textBlock5.Requirements.Add(new AdaptiveRequirement("adaptiveCards", "*"));

            Assert.AreEqual(FallbackType.None, textBlock5.FallbackType);

            card.Body.Add(textBlock5);

            var dispatcher = CoreApplication.MainView.CoreWindow.Dispatcher;

            Exception testException = null;

            // Need to move the test to the UI Thread
            await dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
            {
                try
                {
                    AdaptiveCardRenderer renderer     = new AdaptiveCardRenderer();
                    RenderedAdaptiveCard renderedCard = renderer.RenderAdaptiveCard(card);

                    Assert.AreEqual(3, renderedCard.Warnings.Count);
                    Assert.AreEqual("Performing fallback for element of type \"TextBlock\" (fallback element type \"TextBlock\")", renderedCard.Warnings[0].Message);
                    Assert.AreEqual("Dropping element of type \"TextBlock\" for fallback", renderedCard.Warnings[1].Message);
                    Assert.AreEqual("No Renderer found for type: TextBlock", renderedCard.Warnings[2].Message); //Issue #3418
                }
                catch (Exception thrown)
                {
                    testException = thrown;
                }
            });

            if (testException != null)
            {
                throw testException;
            }
        }
예제 #16
0
        private async Task <Tuple <string, StorageFile, StorageFile, UIElement> > RenderCard(FileViewModel cardFile, FileViewModel hostConfigFile)
        {
            string             error = null;
            RenderTargetBitmap rtb   = null;
            string             roundTrippedJsonString = null;

            try
            {
                AdaptiveHostConfig hostConfig = AdaptiveHostConfig.FromJsonString(hostConfigFile.Contents).HostConfig;

                if (hostConfig == null)
                {
                    error = "Parsing hostConfig failed";
                }

                else
                {
                    AdaptiveCard card = AdaptiveCard.FromJsonString(cardFile.Contents).AdaptiveCard;

                    if (card == null)
                    {
                        error = "Parsing card failed";
                    }

                    else
                    {
                        roundTrippedJsonString = card.ToJson().ToString();
                        card = AdaptiveCard.FromJsonString(roundTrippedJsonString).AdaptiveCard;

                        var renderer = new AdaptiveCardRenderer()
                        {
                            HostConfig = hostConfig
                        };

                        if (hostConfigFile.Name.Contains("windows-timeline"))
                        {
                            renderer.SetFixedDimensions(320, 180);
                            CurrentCardVisualWidth = 320;
                        }
                        else if (hostConfigFile.Name.Contains("windows-live-tile"))
                        {
                            renderer.SetFixedDimensions(310, 310);
                            CurrentCardVisualWidth = 310;
                        }
                        else
                        {
                            CurrentCardVisualWidth = 400;
                        }

                        FrameworkElement xaml = renderer.RenderAdaptiveCard(card).FrameworkElement as FrameworkElement;

                        if (xaml == null)
                        {
                            error = "Rendering card failed";
                        }

                        else
                        {
                            xaml = new Border()
                            {
                                Background       = new SolidColorBrush(Colors.White),
                                Child            = xaml,
                                IsHitTestVisible = false // Disable HitTest so that mouse pointer can't accidently hover over a button
                            };

                            // The theme is important to set since it'll ensure buttons/inputs appear correctly
                            if (hostConfigFile.Name.Contains("windows-notification"))
                            {
                                xaml.RequestedTheme = ElementTheme.Dark;
                            }
                            else
                            {
                                xaml.RequestedTheme = ElementTheme.Light;
                            }

                            CurrentCardVisual = xaml;

                            ExpandShowCards(xaml);
                            NormalizeTimePickers(xaml);
                            await WaitOnAllImagesAsync(xaml);

                            rtb = new RenderTargetBitmap();
                            await rtb.RenderAsync(CurrentCardVisual);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                error = ex.ToString();
            }

            StorageFile file  = null;
            StorageFile file2 = null;

            if (error == null)
            {
                file = await _tempResultsFolder.CreateFileAsync("Result.png", CreationCollisionOption.GenerateUniqueName);

                file2 = await _tempResultsFolder.CreateFileAsync("Result.json", CreationCollisionOption.GenerateUniqueName);

                // https://basquang.wordpress.com/2013/09/26/windows-store-8-1-save-visual-element-to-bitmap-image-file/
                var buffer = await rtb.GetPixelsAsync();

                using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);

                    encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, (uint)rtb.PixelWidth, (uint)rtb.PixelHeight, 96, 96, buffer.ToArray());

                    // Set the size of the card so that it can be rendered just like the bitmap
                    if (CurrentCardVisual is FrameworkElement fe)
                    {
                        fe.Width  = rtb.PixelWidth;
                        fe.Height = rtb.PixelHeight;
                    }

                    await encoder.FlushAsync();
                }

                if (roundTrippedJsonString != null)
                {
                    await Windows.Storage.FileIO.WriteTextAsync(file2, roundTrippedJsonString);
                }
            }

            return(new Tuple <string, StorageFile, StorageFile, UIElement>(error, file, file2, CurrentCardVisual));
        }
예제 #17
0
        public static async Task <RenderedTestResult> RenderCard(FileViewModel cardFile, FileViewModel hostConfigFile)
        {
            string           error = null;
            string           roundTrippedJsonString = null;
            FrameworkElement xaml        = null;
            double           cardWidth   = 400;
            WeakReference    weakRefCard = null;

            try
            {
                AdaptiveHostConfig hostConfig = null;
                if (hostConfigFile.Contents != null)
                {
                    hostConfig = AdaptiveHostConfig.FromJsonString(hostConfigFile.Contents).HostConfig;

                    if (hostConfig == null)
                    {
                        error = "Parsing hostConfig failed";
                    }
                }

                if (error == null)
                {
                    AdaptiveCard card = AdaptiveCard.FromJsonString(cardFile.Contents).AdaptiveCard;

                    if (card == null)
                    {
                        error = "Parsing card failed";
                    }

                    else
                    {
                        roundTrippedJsonString = card.ToJson().ToString();
                        card = AdaptiveCard.FromJsonString(roundTrippedJsonString).AdaptiveCard;

                        AdaptiveFeatureRegistration featureRegistration = new AdaptiveFeatureRegistration();
                        featureRegistration.Set("acTest", "1.0");

                        var renderer = new AdaptiveCardRenderer()
                        {
                            FeatureRegistration = featureRegistration
                        };

                        if (hostConfig != null)
                        {
                            renderer.HostConfig = hostConfig;
                        }

                        renderer.ResourceResolvers.Set("symbol", new SampleResourceResolver());

                        if (hostConfigFile.Name.Contains(FileLoadHelpers.fixedNonInteractiveName))
                        {
                            renderer.SetFixedDimensions(320, 180);
                            cardWidth = 320;

                            renderer.HostConfig.SupportsInteractivity = false;
                        }

                        RenderedAdaptiveCard renderedCard = renderer.RenderAdaptiveCard(card);
                        weakRefCard = new WeakReference(renderedCard);

                        xaml = renderedCard.FrameworkElement as FrameworkElement;

                        if (xaml == null)
                        {
                            error = "Rendering card failed";
                        }

                        else
                        {
                            xaml = new Border()
                            {
                                Background       = new SolidColorBrush(Colors.White),
                                Child            = xaml,
                                IsHitTestVisible = false // Disable HitTest so that mouse pointer can't accidently hover over a button
                            };

                            // The theme is important to set since it'll ensure buttons/inputs appear correctly
                            if (hostConfigFile.Name.Contains(FileLoadHelpers.testVarientHostConfigName))
                            {
                                xaml.RequestedTheme = ElementTheme.Dark;
                            }
                            else
                            {
                                xaml.RequestedTheme = ElementTheme.Light;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                error = ex.ToString();
            }

            return(new RenderedTestResult
            {
                Error = error,
                RoundTrippedJSON = roundTrippedJsonString,
                Tree = xaml,
                CardWidth = cardWidth,
                WeakCard = weakRefCard
            });
        }
예제 #18
0
        public static async Task <RenderedTestResult> RenderCard(FileViewModel cardFile, FileViewModel hostConfigFile, Dictionary <string, IAdaptiveCardResourceResolver> resourceResolvers)
        {
            string           error = null;
            string           roundTrippedJsonString = null;
            FrameworkElement xaml        = null;
            double           cardWidth   = 400;
            WeakReference    weakRefCard = null;

            try
            {
                AdaptiveHostConfig hostConfig = AdaptiveHostConfig.FromJsonString(hostConfigFile.Contents).HostConfig;

                if (hostConfig == null)
                {
                    error = "Parsing hostConfig failed";
                }

                else
                {
                    AdaptiveCard card = AdaptiveCard.FromJsonString(cardFile.Contents).AdaptiveCard;

                    if (card == null)
                    {
                        error = "Parsing card failed";
                    }

                    else
                    {
                        roundTrippedJsonString = card.ToJson().ToString();
                        card = AdaptiveCard.FromJsonString(roundTrippedJsonString).AdaptiveCard;

                        AdaptiveFeatureRegistration featureRegistration = new AdaptiveFeatureRegistration();
                        featureRegistration.Set("acTest", "1.0");

                        var renderer = new AdaptiveCardRenderer()
                        {
                            HostConfig          = hostConfig,
                            FeatureRegistration = featureRegistration
                        };

                        foreach (var resourceResolver in resourceResolvers)
                        {
                            renderer.ResourceResolvers.Set(resourceResolver.Key, resourceResolver.Value);
                        }

                        if (hostConfigFile.Name.Contains("windows-timeline"))
                        {
                            renderer.SetFixedDimensions(320, 180);
                            cardWidth = 320;
                        }
                        else if (hostConfigFile.Name.Contains("windows-live-tile"))
                        {
                            renderer.SetFixedDimensions(310, 310);
                            cardWidth = 310;
                        }

                        RenderedAdaptiveCard renderedCard = renderer.RenderAdaptiveCard(card);
                        weakRefCard = new WeakReference(renderedCard);

                        xaml = renderedCard.FrameworkElement as FrameworkElement;

                        if (xaml == null)
                        {
                            error = "Rendering card failed";
                        }

                        else
                        {
                            xaml = new Border()
                            {
                                Background       = new SolidColorBrush(Colors.White),
                                Child            = xaml,
                                IsHitTestVisible = false // Disable HitTest so that mouse pointer can't accidently hover over a button
                            };

                            // The theme is important to set since it'll ensure buttons/inputs appear correctly
                            if (hostConfigFile.Name.Contains("windows-notification"))
                            {
                                xaml.RequestedTheme = ElementTheme.Dark;
                            }
                            else
                            {
                                xaml.RequestedTheme = ElementTheme.Light;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                error = ex.ToString();
            }

            return(new RenderedTestResult
            {
                Error = error,
                RoundTrippedJSON = roundTrippedJsonString,
                Tree = xaml,
                CardWidth = cardWidth,
                WeakCard = weakRefCard
            });
        }
예제 #19
0
        private static RenderedAdaptiveCard Render(string cardJson, bool hasActions, TypedEventHandler <RenderedAdaptiveCard, AdaptiveActionEventArgs> actionHandler = null)
        {
            try
            {
                var renderer = new AdaptiveCardRenderer();

                // Constructing HostConfig from object model isn't supported yet, have to use JSON
                var hostConfigResult = AdaptiveHostConfig.FromJsonString(HOST_CONFIG);
                if (hostConfigResult.HostConfig != null)
                {
                    renderer.HostConfig = hostConfigResult.HostConfig;
                }
                else
                {
                    throw new Exception("HostConfig failed to parse");
                }

                //renderer.SetHostConfig(new AdaptiveHostConfig()
                //{
                //    AdaptiveCard = new AdaptiveCardConfig()
                //    {
                //        BackgroundColor = Colors.Transparent,
                //        Padding = new AdaptiveSpacingDefinition()
                //        {
                //            Bottom = 0,
                //            Left = 0,
                //            Right = 0,
                //            Top = 0
                //        }
                //    },
                //    Colors = new AdaptiveColorsConfig()
                //    {
                //        Default = new AdaptiveColorConfig()
                //        {
                //            Normal = Colors.White,
                //            Subtle = new Color() { A = 153, R = 255, G = 255, B = 255 }
                //        }
                //    }
                //});

                var cardResult = AdaptiveCard.FromJsonString(cardJson);
                if (cardResult.AdaptiveCard == null)
                {
                    throw new Exception("Failed to parse card");
                }

                var result = renderer.RenderAdaptiveCard(cardResult.AdaptiveCard);
                if (result.FrameworkElement == null)
                {
                    throw new Exception("Failed to render card");
                }

                if (actionHandler != null)
                {
                    // Wire up action click handler
                    result.Action += actionHandler;
                }

                return(result);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
                PreviewToast.SendRenderingError(ex);
                return(null);
            }
        }