Beispiel #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);
        }
Beispiel #2
0
        public static AdaptiveCard Parse(string json)
        {
            AdaptiveElementParserRegistration elementRegistration = new AdaptiveElementParserRegistration();

            elementRegistration.Set("ActionSet", new ActionSetParser());

            return(AdaptiveCard.FromJsonString(json, elementRegistration, null).AdaptiveCard);
        }
        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");
            });
        }
Beispiel #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);
        }
Beispiel #5
0
        /// <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);
        }
Beispiel #6
0
        public void ActionParserRegistraton_CustomActionTest()
        {
            AdaptiveActionParserRegistration  actionParserRegistration  = new AdaptiveActionParserRegistration();
            AdaptiveElementParserRegistration elementParserRegistration = new AdaptiveElementParserRegistration();
            List <AdaptiveWarning>            warnings = new List <AdaptiveWarning>();

            actionParserRegistration.Set("TestCustomAction", new TestActionParser());
            IAdaptiveActionParser testActionParserRetrieved = actionParserRegistration.Get("TestCustomAction");

            Assert.IsNotNull(testActionParserRetrieved);
            Assert.IsNotNull(testActionParserRetrieved as TestActionParser);

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

            AdaptiveCard card = AdaptiveCard.FromJsonString(testCard, elementParserRegistration, actionParserRegistration).AdaptiveCard;

            Assert.IsNotNull(card);

            Assert.AreEqual(1, card.Actions.Count);

            IAdaptiveActionElement action = card.Actions[0];

            Assert.IsNotNull(action);

            Assert.AreEqual(ActionType.Custom, action.ActionType);
            Assert.AreEqual("TestCustomAction", action.ActionTypeString);

            TestCustomAction customElement = card.Actions[0] as TestCustomAction;

            Assert.IsNotNull(customElement);

            Assert.AreEqual(ActionType.Submit, customElement.InternalSubmitAction.ActionType);
        }
        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);
            }
        }
Beispiel #8
0
        public void ElementParserRegistraton_CustomElementTest()
        {
            AdaptiveActionParserRegistration  actionParserRegistration  = new AdaptiveActionParserRegistration();
            AdaptiveElementParserRegistration elementParserRegistration = new AdaptiveElementParserRegistration();
            List <AdaptiveWarning>            warnings = new List <AdaptiveWarning>();

            elementParserRegistration.Set("TestCustomElement", new TestElementParser());
            IAdaptiveElementParser testElementParserRetrieved = elementParserRegistration.Get("TestCustomElement");

            Assert.IsNotNull(testElementParserRetrieved);
            Assert.IsNotNull(testElementParserRetrieved as TestElementParser);

            String testCard =
                "{" +
                "   \"type\":\"AdaptiveCard\"," +
                "   \"version\":\"1.0\"," +
                "   \"body\":" +
                "   [" +
                "       {" +
                "           \"type\":\"TestCustomElement\"," +
                "           \"internalTextBlock\":" +
                "           {" +
                "               \"type\":\"TextBlock\"," +
                "               \"text\":\"Here is some text\"" +
                "           }" +
                "       }" +
                "   ]" +
                "}";

            AdaptiveCard card = AdaptiveCard.FromJsonString(testCard, elementParserRegistration, actionParserRegistration).AdaptiveCard;

            Assert.IsNotNull(card);

            Assert.AreEqual(1, card.Body.Count);

            IAdaptiveCardElement cardElement = card.Body[0];

            Assert.IsNotNull(cardElement);

            Assert.AreEqual(ElementType.Custom, cardElement.ElementType);
            Assert.AreEqual("TestCustomElement", cardElement.ElementTypeString);

            TestCustomElement customElement = card.Body[0] as TestCustomElement;

            Assert.IsNotNull(customElement);

            Assert.AreEqual(ElementType.TextBlock, customElement.InternalTextBlock.ElementType);
        }
Beispiel #9
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);
        }
Beispiel #10
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);
            }
        }
Beispiel #11
0
        public static UIElement RenderFromCard(AdaptiveCards.AdaptiveCard card)
        {
            try
            {
                var uwpCard = AdaptiveCard.FromJsonString(card.ToJson()).AdaptiveCard;

                var renderer = Create();
                return(renderer.RenderAdaptiveCard(uwpCard).FrameworkElement);
            }
            catch (Exception ex)
            {
                return(new Windows.UI.Xaml.Controls.TextBlock()
                {
                    Text = ex.ToString(),
                    TextWrapping = TextWrapping.Wrap
                });
            }
        }
Beispiel #12
0
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            _userActivityChannel = UserActivityChannel.GetDefault();
            _userActivity        = await _userActivityChannel.GetOrCreateUserActivityAsync("NewBlogPost");

            if (e.Parameter != null)
            {
                HttpClient client = new HttpClient();
                json = await client.GetStringAsync(new Uri("https://adaptivecard.azurewebsites.net/api/AppConsultAdaptiveCards?code=AzSEpdNE/P0c9OFIBjro2vSKwGIlLdBWdc53/jmR7Y9PX2l1Ks0/nQ=="));

                AdaptiveCard card = AdaptiveCard.FromJsonString(json).AdaptiveCard;

                var action = card.Actions.FirstOrDefault();
                if (action != null)
                {
                    if (action.ActionType == ActionType.OpenUrl)
                    {
                        var urlAction = action as AdaptiveOpenUrlAction;
                        await Launcher.LaunchUriAsync(urlAction.Url);
                    }
                }
            }
        }
Beispiel #13
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
            });
        }
Beispiel #14
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));
        }
        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);
            }
        }
Beispiel #16
0
        internal static JsonParseToastResult ParseToast(string json, FeatureSet currFeatureSet)
        {
            JsonToastContent toastContent = null;

            JsonParseToastResult result = new JsonParseToastResult();

            int payloadSize = System.Text.Encoding.UTF8.GetByteCount(json);

            if (payloadSize > PAYLOAD_SIZE_LIMIT)
            {
                result.Errors.Add(new ParseError(ParseErrorType.ErrorButRenderAllowed, $"Your payload exceeds the 5 KB size limit (it is {payloadSize.ToString("N0")} Bytes). Please reduce your payload, or else Windows will not display it."));
            }

            var settings = new JsonSerializerSettings()
            {
                MissingMemberHandling = MissingMemberHandling.Error,
                Error = new EventHandler <ErrorEventArgs>((sender, args) =>
                {
                    HandleError(result.Errors, args);
                }),
                ContractResolver = new DefaultContractResolver()
                {
                    NamingStrategy = new JsonToastNamingStrategy()
                }
            };

            try
            {
                toastContent = JsonConvert.DeserializeObject <JsonToastContent>(json, settings);

                if (toastContent.Type != "AdaptiveCard")
                {
                    result.Errors.Add(new ParseError(ParseErrorType.ErrorButRenderAllowed, "\"type\": \"AdaptiveCard\" must be specified in your payload."));
                }
                if (toastContent.Version == null)
                {
                    result.Errors.Add(new ParseError(ParseErrorType.ErrorButRenderAllowed, "\"version\" property must be specified in your payload."));
                }

                var actionReg = new AdaptiveActionParserRegistration();
                // Can't override the Submit parser so can't know whether dev actually sent -ms-systemActivationType="dismiss" or if we translated it
                actionReg.Set("MsAction.Dismiss", new DismissActionParser(result.Errors));
                actionReg.Set("MsAction.Snooze", new SnoozeActionParser(result.Errors));


                AdaptiveElementParserRegistration elementRegistration = new AdaptiveElementParserRegistration();
                elementRegistration.Set("ActionSet", new ActionSetParser());

                var cardParseResult = AdaptiveCard.FromJsonString(json, elementRegistration, actionReg);
                toastContent.Card = cardParseResult.AdaptiveCard;

                foreach (var error in cardParseResult.Errors)
                {
                    result.Errors.Add(new ParseError(ParseErrorType.ErrorButRenderAllowed, error.Message));
                }
                foreach (var warning in cardParseResult.Warnings)
                {
                    result.Errors.Add(new ParseError(ParseErrorType.Warning, warning.Message));
                }
            }
            catch (Exception ex)
            {
                // Json parse exceptions are handled by the error handler and already reported
                if (!(ex is JsonReaderException))
                {
                    result.Errors.Add(new ParseError(ParseErrorType.Error, ex.Message));
                }
            }

            result.Content = toastContent;

            return(result);
        }
Beispiel #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
            });
        }
        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));
        }