protected override Task TransformAsync(AdaptiveBlock block, AdaptiveBlockTransformResult <AdaptiveCard> result)
 {
     try
     {
         result.Result = TransformToCard(block);
     }
     catch (Exception ex)
     {
         result.Errors.Add(ex.ToString());
     }
     return(Task.CompletedTask);
 }
        public async void Update(AdaptiveBlockContent block, AdaptiveBlock sourceBlock, PreviewBlockHostViewModel args)
        {
            MyPreviewToast.Properties = new PreviewToastProperties()
            {
                DisplayName     = args.AppName,
                Square44x44Logo = args.AppLogo
            };

            ToastContent content = (await new AdaptiveBlockToToastContentTransformer().TransformAsync(sourceBlock)).Result;

            MyPreviewToast.Initialize(content.GetXml());
        }
        protected override async Task LoadPayloadAsync(string payload)
        {
            _lastParseResult = AdaptiveBlock.Parse(payload);
            CurrentBlock     = _lastParseResult?.Block;

            if (_lastParseResult.Block != null)
            {
                await _lastParseResult.Block.ResolveAsync();
            }

            PreviewBlockHostViewModel updateArgs = new PreviewBlockHostViewModel()
            {
                BlockContent = _lastParseResult.Block?.View?.Content
            };

            switch (base.Name)
            {
            case "OfficeFile.json":
                updateArgs.AssignApp("PowerPoint", "PowerPoint");
                break;

            case "SkypeCallHistory.json":
                updateArgs.AssignApp("Skype", "Skype");
                break;

            case "SummerRetreats.json":
            case "GitHubUserActivity.json":
                updateArgs.AssignApp("Edge", "Edge");
                break;

            case "GoogleDocsSlide.json":
                updateArgs.AssignApp("Google Slides", "GoogleSlides");
                break;
            }

            foreach (var preview in GetPreviews())
            {
                try
                {
                    preview.Update(_lastParseResult.Block?.View?.Content, _lastParseResult.Block, updateArgs);
                }
                catch { }
            }

            RichRendererPreviewPage.RenderNewBlock(_lastParseResult.Block);
            TransformedCardPreviewPage.RenderNewBlock(_lastParseResult.Block);

            if (_lastParseResult != null)
            {
                this.MakeErrorsLike(_lastParseResult.Errors.ToList());
            }
        }
        private static async Task SendWebNotificationAsync(AdaptiveBlock block, string blockJson, Device device)
        {
            var transformResult = (await new AdaptiveBlockToWebNotificationTransformer().TransformAsync(block));

            if (transformResult.Result == null)
            {
                throw new Exception(string.Join("\n", transformResult.Errors));
            }
            else
            {
                await PushNotificationsWeb.SendAsync(device.Identifier, JsonConvert.SerializeObject(transformResult.Result));
            }
        }
 public static async void RenderNewBlock(AdaptiveBlock block)
 {
     if (Current != null)
     {
         try
         {
             await Current.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, delegate
             {
                 Current.CurrentAdaptiveBlock = block;
             });
         }
         catch { }
     }
 }
        public void Update(AdaptiveBlockContent block, AdaptiveBlock sourceBlock, PreviewBlockHostViewModel args)
        {
            var viewModel = new PreviewEchoSpotViewModel();

            var consumer = new AdaptiveBlockConsumer(AdaptiveBlock.Parse(sourceBlock.ToJson()).Block, new AdaptiveBlockConsumerProperties());

            if (consumer.ConsumeContent(out var contentConsumer))
            {
                if (contentConsumer.ConsumeText(out var text))
                {
                    viewModel.Title = text.Text;
                }

                if (contentConsumer.ConsumeText(out var textSubtitle))
                {
                    viewModel.Subtitle = textSubtitle.Text;
                }

                // In this case, if we only have a profile image, we'd rather use it as the background image
                // But if we have something to use as both the background and profile, then profile should be used.

                var backgroundImageRequest = AdaptiveBlockContentConsumer.ImageMatchRequest.ForBackgroundImage();

                var profileOrIconImageRequest = new AdaptiveBlockContentConsumer.ImageMatchRequest()
                {
                    RequiredHint =
                    {
                        AdaptiveBlockImageCategoryHints.Profile,
                        AdaptiveBlockImageCategoryHints.Icon
                    }
                };

                contentConsumer.ConsumeImages(backgroundImageRequest, profileOrIconImageRequest);

                if (backgroundImageRequest.ImageResult != null)
                {
                    viewModel.BackgroundImage = backgroundImageRequest.ImageResult.Url;
                }

                if (profileOrIconImageRequest.ImageResult != null)
                {
                    viewModel.ProfileImage = profileOrIconImageRequest.ImageResult.Url;
                }
            }

            DataContext = viewModel;

            //DataContext = sourceBlock;
        }
Exemple #7
0
        public void Update(AdaptiveBlockContent block, AdaptiveBlock sourceBlock, PreviewBlockHostViewModel args)
        {
            DataContext = block;

            var icon = block.GetIconImageOrBestFit();

            if (icon?.Url != null)
            {
                IconImageBrush.ImageSource = new BitmapImage(new Uri(icon.Url));
                IconImage.Visibility       = Visibility.Visible;

                IconImage.Margin = new Thickness(icon.Hints.Category.Contains(AdaptiveBlockImageCategoryHints.Icon) ? 8 : 0);

                if (icon.BackgroundColor != null)
                {
                    //IconBackground.Fill = new SolidColorBrush(icon.BackgroundColor);
                }
                else
                {
                    IconBackground.Fill = new SolidColorBrush(Colors.LightGray);
                }
            }
            else
            {
                IconImage.Visibility = Visibility.Collapsed;
            }

            var actions = block.GetSimplifiedActions();

            if (actions.Any())
            {
                Buttons.Visibility = Visibility.Visible;

                FirstButton.Text = actions.First().Title;

                if (actions.Count() > 1)
                {
                    MoreButton.Visibility = Visibility.Visible;
                }
                else
                {
                    MoreButton.Visibility = Visibility.Collapsed;
                }
            }
            else
            {
                Buttons.Visibility = Visibility.Collapsed;
            }
        }
Exemple #8
0
        public static bool HasMoreThanOneBlock(this AdaptiveBlock block)
        {
            var detailedBlocks = block.View?.Content?.DetailedBlocks;

            if (detailedBlocks != null && detailedBlocks.Count > 0)
            {
                if (detailedBlocks.Count > 1)
                {
                    return(true);
                }

                return(detailedBlocks[0].HasMoreThanOneBlock());
            }

            return(false);
        }
        public async void Update(AdaptiveBlockContent block, AdaptiveBlock sourceBlock, PreviewBlockHostViewModel args)
        {
            AdaptiveCardContainer.Child = null;
            AdaptiveCards.Rendering.Uwp.AdaptiveCard card = null;

            try
            {
                var cardObj = sourceBlock.View.RichContent.FirstOrDefault(i => i.TargetedExperiences.Contains("Microsoft.Outlook.ActionableMessage") && i.ContentType == "application/vnd.microsoft.card.adaptive")?.Content;
                if (cardObj != null)
                {
                    string cardJson   = cardObj.ToString();
                    var    parsedCard = SharedAdaptiveCardRenderer.Parse(cardJson);
                    if (parsedCard != null)
                    {
                        card = parsedCard;
                    }
                }
            }
            catch { }

            if (card == null)
            {
                try
                {
                    var transformer = new AdaptiveBlockToCardTransformer()
                    {
                        Properties = new AdaptiveBlockToCardTransformerProperties()
                    };
                    var sharedCard = (await transformer.TransformAsync(sourceBlock)).Result;

                    card = SharedAdaptiveCardRenderer.ConvertToUwpCard(sharedCard);
                }
                catch
                {
                }
            }

            try
            {
                if (card != null)
                {
                    AdaptiveCardContainer.Child = _cardRenderer.Value.RenderAdaptiveCard(card).FrameworkElement;
                }
            }
            catch { }
        }
        private async void RenderBlock(AdaptiveBlock block)
        {
            var transformer = new AdaptiveBlockToCardTransformer();

            var sharedCard = (await transformer.TransformAsync(block)).Result;

            if (sharedCard != null)
            {
                TextBoxCardPayload.Text = sharedCard.ToJson();
            }

            var uwpCard = SharedAdaptiveCardRenderer.ConvertToUwpCard(sharedCard);

            RenderCard(CardPreview, uwpCard, m_cardRenderer);
            RenderCard(CardPreviewTeams, uwpCard, m_cardRendererTeams);
            RenderCard(CardPreviewCortana, uwpCard, m_cardRendererCortana);
        }
Exemple #11
0
        public void Update(AdaptiveBlockContent block, AdaptiveBlock sourceBlock, PreviewBlockHostViewModel args)
        {
            LogoOrAttributionIcon.Source = args.GetAppLogoImageSource();

            TextBlockTitle.Text = block.Text?.FirstOrDefault()?.Text;

            try
            {
                if (sourceBlock.View.Attributes != null)
                {
                    var attrUrl = sourceBlock.View.Attributes.AttributionIcon?.GetIconForTheme(AdaptiveThemes.Dark)?.Url;
                    if (attrUrl != null)
                    {
                        LogoOrAttributionIcon.Source = new BitmapImage(new Uri(attrUrl));
                    }
                }
            }
            catch { }
        }
 public void RemoveBlock(AdaptiveBlock block)
 {
     try
     {
         if (CurrentBlock != null)
         {
             if (CurrentBlock == block)
             {
                 Payload = "";
             }
             else if (CurrentBlock.RemoveBlock(block))
             {
                 Payload = CurrentBlock.ToJson();
             }
         }
     }
     catch (Exception ex)
     {
     }
 }
        public void Update(AdaptiveBlockContent block, AdaptiveBlock sourceBlock, PreviewBlockHostViewModel args)
        {
            DataContext = args;

            RectangleThumbnail.Visibility = Visibility.Collapsed;

            TextBlockTitle.Text = block.Title;

            TextBlockAttributionOrSubtitle.Text = block.Subtitle ?? sourceBlock.View.Attributes?.AttributionText?.Text ?? "";

            if (block.FirstImage?.Url != null)
            {
                try
                {
                    ImageBrushThumbnail.ImageSource = new BitmapImage(new Uri(block.FirstImage.Url));
                    RectangleThumbnail.Visibility   = Visibility.Visible;
                }
                catch { }
            }
        }
        private static async Task SendWindowsNotification(AdaptiveBlock block, string blockJson, Device device)
        {
            string bodyXml;
            var    transformResult = await new AdaptiveBlockToToastContentTransformer().TransformAsync(block);

            if (transformResult.Result != null)
            {
                bodyXml = transformResult.Result.GetContent();
            }
            else
            {
                bodyXml = "<toast><visual><binding template=\"ToastGeneric\"><text>" + blockJson + "</text></binding></visual></toast>";
            }

            var resp = PushNotificationsWNS.Push(bodyXml, device.Identifier, WindowsSecret, WindowsPackageSid, PushNotificationsWNS.NotificationType.Toast);

            if (resp != System.Net.HttpStatusCode.OK)
            {
                throw new Exception(resp.ToString());
            }
        }
        private AdaptiveCard TransformToCard(AdaptiveBlock block)
        {
            AdaptiveCard card = new AdaptiveCard("1.0");

            if (block != null)
            {
                bool first = true;
                foreach (var el in TransformBlockToElements(block, new AdaptiveBlockTransformContext(this)))
                {
                    if (first)
                    {
                        first = false;
                    }
                    else
                    {
                        el.Separator = true;
                    }

                    card.Body.Add(el);
                }
            }

            return(card);
        }
        public void Update(AdaptiveBlockContent block, AdaptiveBlock sourceBlock, PreviewBlockHostViewModel args)
        {
            try
            {
                Pages.Children.Clear();

                foreach (var b in block.GetFinalBlocks())
                {
                    Pages.Children.Add(new PreviewRichWatchBlock()
                    {
                        DataContext = b
                    });
                }

                if (block.Actions.Any())
                {
                    Pages.Children.Add(new PreviewRichWatchActionsPage()
                    {
                        DataContext = block.GetSimplifiedActions()
                    });
                }
            }
            catch { }
        }
        public void Update(AdaptiveBlockContent block, AdaptiveBlock sourceBlock, PreviewBlockHostViewModel args)
        {
            TextBlockAppNameOrAttribution.Text = args.AppName;
            LogoOrAttributionIcon.Source       = args.GetAppLogoImageSource();

            TextBlockTitle.Text = block.Text.FirstOrDefault()?.Text;

            try
            {
                if (sourceBlock.View.Attributes != null)
                {
                    if (sourceBlock.View.Attributes.AttributionText?.Text != null)
                    {
                        TextBlockAppNameOrAttribution.Text = sourceBlock.View.Attributes.AttributionText.Text;
                    }

                    if (sourceBlock.View.Attributes.AttributionIcon?.Url != null)
                    {
                        LogoOrAttributionIcon.Source = new BitmapImage(new Uri(sourceBlock.View.Attributes.AttributionIcon?.Url));
                    }
                }
            }
            catch { }
        }
Exemple #18
0
        public static bool HasMultipleDetailedBlocks(this AdaptiveBlock block)
        {
            var detailedBlocks = block.View?.Content?.DetailedBlocks;

            return(detailedBlocks != null && detailedBlocks.Count > 1);
        }
        protected override Task TransformAsync(AdaptiveBlock block, AdaptiveBlockTransformResult <ToastContent> result)
        {
            ToastContent content = new ToastContent()
            {
                Visual = new ToastVisual()
                {
                    BindingGeneric = new ToastBindingGeneric()
                }
            };

            var finalBlocks = block.GetFinalBlocks();
            var firstBlock  = finalBlocks.First();


            var firstBlockContent = firstBlock.View?.Content;

            if (firstBlockContent != null)
            {
                foreach (var t in firstBlockContent.Text.Take(3))
                {
                    content.Visual.BindingGeneric.Children.Add(new AdaptiveText()
                    {
                        Text = t.Text
                    });
                }

                var profileOrIconImageRequest = new AdaptiveBlockContentConsumer.ImageMatchRequest()
                {
                    RequiredHint =
                    {
                        AdaptiveBlockImageCategoryHints.Profile,
                        AdaptiveBlockImageCategoryHints.Icon
                    }
                };

                var heroImageRequest = new AdaptiveBlockContentConsumer.ImageMatchRequest()
                {
                    HintsToAvoid =
                    {
                        AdaptiveBlockImageCategoryHints.Icon
                    }
                };

                AdaptiveBlockContentConsumer.MatchImages(firstBlockContent, profileOrIconImageRequest, heroImageRequest);

                if (heroImageRequest.ImageResult != null)
                {
                    content.Visual.BindingGeneric.HeroImage = new ToastGenericHeroImage()
                    {
                        Source = heroImageRequest.ImageResult.Url
                    };
                }

                if (profileOrIconImageRequest.ImageResult != null)
                {
                    content.Visual.BindingGeneric.AppLogoOverride = new ToastGenericAppLogo()
                    {
                        Source   = profileOrIconImageRequest.ImageResult.Url,
                        HintCrop = profileOrIconImageRequest.ImageResult.Hints.Category.Contains(AdaptiveBlockImageCategoryHints.Profile) ? ToastGenericAppLogoCrop.Circle : ToastGenericAppLogoCrop.Default
                    };
                }

                if (finalBlocks.Count() > 1)
                {
                    foreach (var extraBlock in finalBlocks.Skip(1))
                    {
                        if (extraBlock.View?.Content != null)
                        {
                            content.Visual.BindingGeneric.Children.Add(CreateGroup(extraBlock.View.Content));
                        }
                    }
                }

                if (block.View.Attributes?.AttributionText?.Text != null)
                {
                    content.Visual.BindingGeneric.Attribution = new ToastGenericAttributionText()
                    {
                        Text = block.View.Attributes?.AttributionText?.Text
                    };
                }

                if (firstBlockContent.Actions.Any())
                {
                    content.Actions = new ToastActionsCustom();
                    var toastActions = content.Actions as ToastActionsCustom;

                    foreach (var a in firstBlockContent.Actions)
                    {
                        // Quick reply style
                        if (a is AdaptiveAction singleFinalAction && a.Inputs.Count == 1 && a.Inputs.First() is AdaptiveTextInputBlock singleTextInput)
                        {
                            toastActions.Inputs.Add(new ToastTextBox(singleTextInput.Id)
                            {
                                PlaceholderContent = singleTextInput.Placeholder
                            });
                            var button = CreateButton(singleFinalAction);
                            button.TextBoxId = singleTextInput.Id;
                            toastActions.Buttons.Add(button);
                        }
                        else
                        {
                            foreach (var input in a.Inputs)
                            {
                                if (input is AdaptiveTextInputBlock textInput)
                                {
                                    toastActions.Inputs.Add(new ToastTextBox(textInput.Id)
                                    {
                                        PlaceholderContent = textInput.Placeholder,
                                        Title = textInput.Title
                                    });
                                }

                                else if (input is AdaptiveChoiceSetInputBlock choiceInput)
                                {
                                    var selectionBox = new ToastSelectionBox(choiceInput.Id)
                                    {
                                        Title = choiceInput.Title
                                    };
                                    foreach (var val in choiceInput.Choices)
                                    {
                                        selectionBox.Items.Add(new ToastSelectionBoxItem(val.Value, val.Title));
                                    }
                                    toastActions.Inputs.Add(selectionBox);
                                }
                            }

                            List <AdaptiveAction> finalActions;
                            if (a is AdaptiveSharedInputActions sharedActions)
                            {
                                finalActions = sharedActions.Actions;
                            }
                            else if (a is AdaptiveAction finalAction)
                            {
                                finalActions = new List <AdaptiveAction>()
                                {
                                    finalAction
                                };
                            }
                            else
                            {
                                finalActions = new List <AdaptiveAction>();
                            }

                            foreach (var finalAction in finalActions)
                            {
                                toastActions.Buttons.Add(CreateButton(finalAction));
                            }
                        }
                    }
                }
Exemple #20
0
        protected override Task TransformAsync(AdaptiveBlock block, AdaptiveBlockTransformResult <UserActivity> result)
        {
            var content = block.View?.Content;

            if (content != null)
            {
                if (content.Title != null)
                {
                    m_activity.VisualElements.DisplayText = content.Title;
                }

                if (content.Subtitle != null)
                {
                    m_activity.VisualElements.Description = content.Subtitle;
                }
            }

            var cardContent = block.View?.RichContent?.FirstOrDefault(i => i.ContentType == "application/vnd.microsoft.card.adaptive" && i.TargetedExperiences != null && i.TargetedExperiences.Contains("Microsoft.UserActivities.Hero"))?.Content;

            if (cardContent != null)
            {
                m_activity.VisualElements.Content = AdaptiveCardBuilder.CreateAdaptiveCardFromJson(cardContent.ToString());
            }
            else if (content != null)
            {
                var backgroundImageRequest = AdaptiveBlockContentConsumer.ImageMatchRequest.ForBackgroundImage();

                AdaptiveBlockContentConsumer.MatchImages(content, backgroundImageRequest);

                if (backgroundImageRequest.ImageResult != null)
                {
                    var adaptiveCard = new AdaptiveCard("1.0");
                    adaptiveCard.BackgroundImage = new Uri(backgroundImageRequest.ImageResult.Url);

                    if (content.Title != null)
                    {
                        adaptiveCard.Body.Add(new AdaptiveTextBlock()
                        {
                            Text     = content.Title,
                            Size     = AdaptiveTextSize.Large,
                            Weight   = AdaptiveTextWeight.Bolder,
                            Wrap     = true,
                            MaxLines = 3
                        });
                    }

                    if (content.Subtitle != null)
                    {
                        adaptiveCard.Body.Add(new AdaptiveTextBlock()
                        {
                            Text     = content.Subtitle,
                            Wrap     = true,
                            MaxLines = 3
                        });
                    }

                    m_activity.VisualElements.Content = AdaptiveCardBuilder.CreateAdaptiveCardFromJson(adaptiveCard.ToJson());
                }
            }

            if (block.View?.Attributes != null)
            {
                var attributes = block.View.Attributes;

                if (attributes.AttributionText != null)
                {
                    m_activity.VisualElements.AttributionDisplayText = attributes.AttributionText.Text;
                }

                var attrIcon = attributes.AttributionIcon?.GetIconForTheme(AdaptiveThemes.Dark);
                if (attrIcon != null)
                {
                    m_activity.VisualElements.Attribution = new UserActivityAttribution(new Uri(attrIcon.Url));
                }
            }

            result.Result = m_activity;
            return(Task.CompletedTask);
        }
Exemple #21
0
 public static AdaptiveBlock GetFirstDetailedBlock(this AdaptiveBlock block)
 {
     return(block.View.Content.DetailedBlocks.First());
 }
Exemple #22
0
 /// <summary>
 /// Note that the block WILL be modified.
 /// </summary>
 /// <param name="block"></param>
 /// <param name="properties"></param>
 public AdaptiveBlockConsumer(AdaptiveBlock block, AdaptiveBlockConsumerProperties properties)
 {
     Block     = block;
     m_content = block.View?.Content;
 }
 public RenderableBlockData(AdaptiveBlock blockSource)
 {
     BlockSource = blockSource;
     Block       = blockSource?.View?.Content;
     Reset();
 }
        public void Update(AdaptiveBlockContent block, AdaptiveBlock sourceBlock, PreviewBlockHostViewModel args)
        {
            DataContext = args;

            GenericContent.Visibility        = Visibility.Collapsed;
            CardContent.Child                = null;
            CardContent.Visibility           = Visibility.Collapsed;
            DocumentContent.Visibility       = Visibility.Collapsed;
            MessageTemplate.Visibility       = Visibility.Collapsed;
            BackgroundImageBrush.ImageSource = null;
            GenericContent.RequestedTheme    = ElementTheme.Light;
            BackgroundOverlay.Visibility     = Visibility.Collapsed;
            TextBlockAttribution.Text        = args.AppName;
            LogoOrAttributionIcon.Source     = args.GetAppLogoImageSource();

            try
            {
                if (sourceBlock.View.Attributes != null)
                {
                    if (sourceBlock.View.Attributes.AttributionText?.Text != null)
                    {
                        TextBlockAttribution.Text = sourceBlock.View.Attributes.AttributionText.Text;
                    }

                    if (sourceBlock.View.Attributes.AttributionIcon?.Url != null)
                    {
                        LogoOrAttributionIcon.Source = new BitmapImage(new Uri(sourceBlock.View.Attributes.AttributionIcon?.Url));
                    }
                }
            }
            catch { }

            try
            {
                var cardObj = sourceBlock.View.RichContent.FirstOrDefault(i => i.TargetedExperiences.Contains("Microsoft.UserActivities.Hero") && i.ContentType == "application/vnd.microsoft.card.adaptive")?.Content;
                if (cardObj != null)
                {
                    string cardJson          = cardObj.ToString();
                    var    cardParseResult   = AdaptiveCards.Rendering.Uwp.AdaptiveCard.FromJsonString(cardJson);
                    string errorsAndWarnings = string.Join("\n", cardParseResult.Errors.Select(i => i.Message));
                    if (cardParseResult.AdaptiveCard != null)
                    {
                        if (!string.IsNullOrWhiteSpace(cardParseResult.AdaptiveCard.BackgroundImage) && Uri.IsWellFormedUriString(cardParseResult.AdaptiveCard.BackgroundImage, UriKind.Absolute))
                        {
                            BackgroundImageBrush.ImageSource             = new BitmapImage(new Uri(cardParseResult.AdaptiveCard.BackgroundImage));
                            cardParseResult.AdaptiveCard.BackgroundImage = "";
                            BackgroundOverlay.Visibility = Visibility.Visible;
                        }

                        var renderedElement = (BackgroundImageBrush.ImageSource != null ? _cardRenderer : _cardRendererLight).Value.RenderAdaptiveCard(cardParseResult.AdaptiveCard).FrameworkElement;
                        CardContent.Child         = renderedElement;
                        CardContent.Visibility    = Visibility.Visible;
                        GenericContent.Visibility = Visibility.Collapsed;
                        return;
                    }
                }
            }
            catch { }

            TextBlockTitle.Text    = block.Title ?? "";
            TextBlockSubtitle.Text = block.Subtitle ?? "";

            var backgroundImg = block.GetBackgroundImage();

            if (backgroundImg?.Url != null)
            {
                try
                {
                    BackgroundImageBrush.ImageSource = new BitmapImage(new Uri(backgroundImg.Url));
                    GenericContent.RequestedTheme    = ElementTheme.Dark;
                    BackgroundOverlay.Visibility     = Visibility.Visible;
                }
                catch { }
            }

            DocumentImageBrush.ImageSource = block.GetHeroImage()?.CreateImageSource();

            if (sourceBlock.Hints.HasCategory("Thing.CreativeWork.DigitalDocument"))
            {
                DocumentContent.Visibility = Visibility.Visible;
            }
            else if (sourceBlock.Hints.HasCategory("Thing.CreativeWork.Message"))
            {
                MessageTemplate.Visibility  = Visibility.Visible;
                MessageTemplate.DataContext = PreviewTimelineWebFullSizeTemplates.PreviewTimelineWebFullSizeMessageViewModel.Create(block);
            }
            else
            {
                GenericContent.Visibility = Visibility.Visible;
            }
        }
Exemple #25
0
        private void SendNotification(string notificationJson)
        {
            try
            {
                var block = AdaptiveBlock.Parse(notificationJson).Block;

                var content = block?.View?.Content;
                if (content != null)
                {
                    var builder = new NotificationCompat.Builder(this, AppClient.CHANNEL_ID)
                                  .SetSmallIcon(Android.Resource.Drawable.abc_btn_switch_to_on_mtrl_00001)
                                  .SetAutoCancel(true)
                                  .SetPriority(1);

                    if (content.Title != null)
                    {
                        builder.SetContentTitle(content.Title);
                    }

                    if (content.Subtitle != null)
                    {
                        builder.SetContentText(content.Subtitle);
                        builder.SetStyle(new NotificationCompat.BigTextStyle()
                                         .BigText(content.Subtitle));
                    }

                    var profileImg = GetBitmap(content.GetProfileImage());
                    var heroImg    = GetBitmap(content.GetHeroImage());

                    if (heroImg != null)
                    {
                        builder.SetLargeIcon(heroImg);

                        builder.SetStyle(new NotificationCompat.BigPictureStyle()
                                         .BigPicture(heroImg)
                                         .BigLargeIcon(profileImg));
                    }
                    else
                    {
                        if (profileImg != null)
                        {
                            builder.SetLargeIcon(profileImg);
                        }

                        // Expandable
                        builder.SetStyle(new NotificationCompat.BigTextStyle()
                                         .BigText(content.Subtitle));
                    }

                    foreach (var action in content.GetSimplifiedActions())
                    {
                        if ((action.Inputs.Count == 0 || action.Inputs.Count == 1 && action.Inputs[0] is AdaptiveTextInputBlock) && action.Command != null)
                        {
                            PendingIntent pendingIntent;
                            if (action.Command is AdaptiveOpenUrlCommand openUrlCommand)
                            {
                                Intent openUrlIntent = new Intent(Intent.ActionView, global::Android.Net.Uri.Parse(openUrlCommand.Url));
                                pendingIntent = PendingIntent.GetActivity(this, 0, openUrlIntent, 0);
                            }
                            else
                            {
                                Intent actionIntent = new Intent(this, typeof(NotificationActionReceiver));
                                actionIntent.SetAction("com.microsoft.InteractiveNotifs.ApiClient.Android.InvokeAction");
                                actionIntent.PutExtra("cmd", JsonConvert.SerializeObject(action.Command));
                                if (action.Inputs.FirstOrDefault() is AdaptiveTextInputBlock tbInputBlock)
                                {
                                    actionIntent.PutExtra("textId", tbInputBlock.Id);
                                }
                                pendingIntent = PendingIntent.GetBroadcast(this, new Random().Next(int.MaxValue), actionIntent, PendingIntentFlags.OneShot);
                            }

                            if (action.Inputs.FirstOrDefault() is AdaptiveTextInputBlock tbInput)
                            {
                                var remoteInput = new global::Android.Support.V4.App.RemoteInput.Builder("text")
                                                  .SetLabel(tbInput.Placeholder ?? action.Title)
                                                  .Build();

                                builder.AddAction(new NotificationCompat.Action.Builder(
                                                      Resource.Drawable.abc_ic_go_search_api_material,
                                                      action.Title,
                                                      pendingIntent)
                                                  .AddRemoteInput(remoteInput)
                                                  .Build());
                            }
                            else
                            {
                                builder.AddAction(Android.Resource.Drawable.abc_btn_check_material, action.Title, pendingIntent);
                            }
                        }
                    }

                    var manager = NotificationManagerCompat.From(this);
                    manager.Notify(1, builder.Build());
                }
            }
            catch { }
        }
 protected abstract Task TransformAsync(AdaptiveBlock block, AdaptiveBlockTransformResult <T> result);
        public override void DidReceiveNotificationRequest(UNNotificationRequest request, Action <UNNotificationContent> contentHandler)
        {
            ContentHandler     = contentHandler;
            BestAttemptContent = (UNMutableNotificationContent)request.Content.MutableCopy();

            try
            {
                NSObject blockObj  = request.Content.UserInfo["block"];
                string   blockJson = blockObj.Description;
                var      block     = AdaptiveBlock.Parse(blockJson).Block;

                var content = block?.View?.Content;
                if (content != null)
                {
                    var actions = content.GetSimplifiedActions().ToArray();
                    if (actions.Any())
                    {
                        // You seemingly can't create notification categories (or create new notifications) from this service

                        //string titles = string.Join(",", actions.Select(i => i.Title));


                        //UNNotificationAction[] unActions = actions.Take(1).Select(i => UNNotificationAction.FromIdentifier("myact", i.Title, UNNotificationActionOptions.None)).ToArray();


                        //string categoryId = "mycat";

                        //var category = UNNotificationCategory.FromIdentifier(
                        //    identifier: categoryId,
                        //    actions: unActions,
                        //    intentIdentifiers: new string[] { },
                        //    options: UNNotificationCategoryOptions.None);

                        //UNUserNotificationCenter.Current.SetNotificationCategories(new NSSet<UNNotificationCategory>(new UNNotificationCategory[] { category }));

                        //var newContent = new UNMutableNotificationContent();
                        //newContent.Title = "New notification";
                        ////newContent.CategoryIdentifier = categoryId;
                        //var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(5, false);

                        //var requestID = "sampleRequest";
                        //var newRequest = UNNotificationRequest.FromIdentifier(requestID, newContent, trigger);

                        //UNUserNotificationCenter.Current.AddNotificationRequest(newRequest, (err) => {
                        //    if (err != null)
                        //    {
                        //        // Do something with error...
                        //    }
                        //});

                        //BestAttemptContent.CategoryIdentifier = categoryId;
                        //BestAttemptContent.Title = "Set category id 3";
                    }
                }
            }
            catch (Exception ex) {
                BestAttemptContent.Subtitle = LimitLength(ex.ToString());
            }


            ContentHandler(BestAttemptContent);
        }
        public async void Update(AdaptiveBlockContent block, AdaptiveBlock sourceBlock, PreviewBlockHostViewModel args)
        {
            try
            {
                m_currSourceBlock   = sourceBlock;
                m_currHostViewModel = args;

                MyPreviewToast.Properties = new PreviewToastProperties()
                {
                    DisplayName     = args.AppName,
                    Square44x44Logo = args.AppLogo
                };



                AdaptiveBlockContent firstFinalBlock;

                if (IsExpanded)
                {
                    firstFinalBlock = sourceBlock.GetFirstFinalBlock().View.Content;
                }
                else
                {
                    firstFinalBlock = block;
                }

                string title    = firstFinalBlock.Title;
                string subtitle = firstFinalBlock.Subtitle;

                var originalText   = firstFinalBlock.Text.ToArray();
                var originalImages = firstFinalBlock.Images.ToArray();

                firstFinalBlock.Text.Clear();

                var firstHeroImg = firstFinalBlock.GetHeroImage();

                var firstProfileImg = firstFinalBlock.GetProfileImage();

                firstFinalBlock.Images.Clear();

                AdaptiveCard card;
                if (IsExpanded)
                {
                    var transformer = new AdaptiveBlockToCardTransformer();
                    card = (await transformer.TransformAsync(sourceBlock)).Result;
                }
                else
                {
                    card = new AdaptiveCard("1.0");
                }

                firstFinalBlock.Text.AddRange(originalText);
                firstFinalBlock.Images.AddRange(originalImages);

                card.AdditionalProperties["title"] = new Dictionary <string, string>()
                {
                    { "text", title }
                };
                if (subtitle != null)
                {
                    card.AdditionalProperties["subtitle"] = new Dictionary <string, string>()
                    {
                        { "text", subtitle }
                    };
                }

                Dictionary <string, Dictionary <string, string> > imagesObject = new Dictionary <string, Dictionary <string, string> >();

                if (firstProfileImg != null)
                {
                    imagesObject["profile"] = new Dictionary <string, string>()
                    {
                        { "url", firstProfileImg.Url },
                        { "style", "person" }
                    };
                }

                if (firstHeroImg != null)
                {
                    imagesObject["card"] = new Dictionary <string, string>()
                    {
                        { "url", firstHeroImg.Url }
                    };
                }

                if (imagesObject.Count > 0)
                {
                    card.AdditionalProperties["images"] = imagesObject;
                }

                MyPreviewToast.InitializeFromJson(card.ToJson(), new NotificationsVisualizerLibrary.PreviewNotificationData());
            }
            catch { }
        }