Exemplo n.º 1
0
        private async Task UpdateActualUserActivityAsync()
        {
            _actualUserActivity.ActivationUri = Payload.ActivationUri;
            _actualUserActivity.ContentType   = Payload.ContentType;
            _actualUserActivity.ContentUri    = Payload.ContentUri;
            _actualUserActivity.FallbackUri   = Payload.FallbackUri;
            _actualUserActivity.VisualElements.Attribution = new UserActivityAttribution()
            {
                IconUri       = Payload.VisualElements.Attribution.IconUri,
                AlternateText = Payload.VisualElements.Attribution.AlternateText,
                AddImageQuery = Payload.VisualElements.Attribution.AddImageQuery
            };
            _actualUserActivity.VisualElements.AttributionDisplayText = Payload.VisualElements.AttributionDisplayText;
            _actualUserActivity.VisualElements.BackgroundColor        = Payload.VisualElements.BackgroundColor;

            if (Payload.VisualElements.Content != null)
            {
                _actualUserActivity.VisualElements.Content = AdaptiveCardBuilder.CreateAdaptiveCardFromJson(Payload.VisualElements.Content.ToString());
            }
            else
            {
                _actualUserActivity.VisualElements.Content = null;
            }

            _actualUserActivity.VisualElements.Description = Payload.VisualElements.Description;
            _actualUserActivity.VisualElements.DisplayText = Payload.VisualElements.DisplayText;

            await _actualUserActivity.SaveAsync();
        }
Exemplo n.º 2
0
        public async void GenerateActivityAsync(string websitePage, string title, string content, string backgroundPath)
        {
            // Get the default UserActivityChannel and query it for our UserActivity. If the activity doesn't exist, one is created.
            UserActivityChannel channel      = UserActivityChannel.GetDefault();
            UserActivity        userActivity = await channel.GetOrCreateUserActivityAsync("MainPage");

            var uri = new Uri("moepicture://" + title + "?action=view");

            // Populate required properties
            userActivity.VisualElements.DisplayText = "MoePicture";
            userActivity.ActivationUri = uri;

            var    folder       = Package.Current.InstalledLocation;
            var    file         = await(await folder.GetFolderAsync("JskyUwpLibs")).GetFileAsync("Activities.json");
            string cardJsonText = await FileIO.ReadTextAsync(file);

            dynamic card = JObject.Parse(cardJsonText);

            card.backgroundImage       = backgroundPath;
            card.body[0].items[0].text = title;
            card.body[0].items[1].text = content;
            cardJsonText = JsonConvert.SerializeObject(card);
            // where jsonCardText is a JSON string that represents the card
            userActivity.VisualElements.Content = AdaptiveCardBuilder.CreateAdaptiveCardFromJson(cardJsonText);

            //Save
            await userActivity.SaveAsync(); //save the new metadata

            // Dispose of any current UserActivitySession, and create a new one.
            currentActivity?.Dispose();
            currentActivity = userActivity.CreateSession();
        }
Exemplo n.º 3
0
        public async Task <UserActivity> UpdateActivityAsync(ISource <BaseTrack> source, BaseTrack track, IEnumerable <BaseTrack> playlist, string token)
        {
            // We do not support these items
            if (track.ServiceType == ServiceType.ITunesPodcast ||
                track.ServiceType == ServiceType.Local ||
                track.ServiceType == ServiceType.Unknown)
            {
                return(null);
            }

            var activity = await _channel.GetOrCreateUserActivityAsync("SoundByte.Playback");

            activity.FallbackUri = new Uri("https://soundbytemedia.com/pages/remote-subsystem");

            var continueText = $"Continue listening to {track.Title} by {track.User.Username}";

            activity.VisualElements.DisplayText = "Now Playing";
            activity.VisualElements.Description = continueText;

            activity.VisualElements.Content = AdaptiveCardBuilder.CreateAdaptiveCardFromJson("{\"$schema\": \"http://adaptivecards.io/schemas/adaptive-card.json\",\"type\":\"AdaptiveCard\",\"backgroundImage\":\"" + track.ArtworkUrl + "\",\"version\": \"1.0\",\"body\":[{\"type\":\"Container\",\"items\":[{\"type\":\"TextBlock\",\"text\":\"Now Playing\",\"weight\":\"bolder\",\"size\":\"large\",\"wrap\":true,\"maxLines\":3},{\"type\":\"TextBlock\",\"text\":\"" + continueText + ".\",\"size\": \"default\",\"wrap\": true,\"maxLines\": 3}]}]}");

            // Set the activation url using shorthand protocol
            activity.ActivationUri = new Uri($"sb://rs?d={EncodeActivityParameters(source, track, playlist, token)}");

            await activity.SaveAsync();

            return(activity);
        }
Exemplo n.º 4
0
        private async Task AddTimelineItem(T newItem)
        {
            UserActivityChannel _userActivityChannel = UserActivityChannel.GetDefault();
            UserActivity        _userActivity        = await _userActivityChannel.GetOrCreateUserActivityAsync("TDN");

            // Fetch the adaptive card JSON
            var adaptiveCard = AdaptiveCards.AdaptiveHeaderDescription;

            // Replace the content.
            adaptiveCard = adaptiveCard.Replace("{backgroundImage}", "");
            adaptiveCard = adaptiveCard.Replace("{name}", newItem.Name);
            adaptiveCard = adaptiveCard.Replace("{description}", newItem.Description);

            // Create the protocol, so when the clicks the Adaptive Card on the Timeline, it will directly launch to the correct image.
            //_userActivity.ActivationUri = new Uri($"my-timeline://details?{_galleryItem.ImageSource.Replace("ms-appx:///Assets/Images/", "")}");

            // Set the display text to the User Activity(e.g. Pike Place market.)
            _userActivity.VisualElements.DisplayText = newItem.Name;

            // Assign the Adaptive Card to the user activity.
            _userActivity.VisualElements.Content = AdaptiveCardBuilder.CreateAdaptiveCardFromJson(adaptiveCard);

            // Save the details user activity.
            await _userActivity.SaveAsync();

            // Dispose of the session and create a new one ready for the next user activity.
            _userActivitySession?.Dispose();
            _userActivitySession = _userActivity.CreateSession();
        }
Exemplo n.º 5
0
        private async Task GenerateActivityAsync(VolItem volItem)
        {
            // Get the default UserActivityChannel and query it for our UserActivity. If the activity doesn't exist, one is created.
            UserActivityChannel channel = UserActivityChannel.GetDefault();

            // The text here should be treated as a title for this activity and should be unique to this app.
            UserActivity userActivity = await channel.GetOrCreateUserActivityAsync("LuoVol." + volItem.Vol.VolNum);

            // Populate required properties: DisplayText and ActivationUri are required.
            userActivity.VisualElements.DisplayText = "Luoo-UWP Timeline activities";

            // The name in the ActivationUri must match the name in the protocol setting in the manifest file (except for the "://" part).
            userActivity.ActivationUri = new Uri("luoo://?volnum=" + volItem.Vol.VolNum);

            // Build the adaptive card from a JSON string.
            userActivity.VisualElements.Content = AdaptiveCardBuilder.CreateAdaptiveCardFromJson(apodTimelineCard.ToJson());

            // Set the mime type of the user activity, in this case, an application.
            userActivity.ContentType = "application/octet-stream";

            // Save the new metadata.
            await userActivity.SaveAsync();

            // Dispose of any current UserActivitySession, and create a new one.
            _currentActivity?.Dispose();
            _currentActivity = userActivity.CreateSession();
        }
        void OnUserActivityRequested(UserActivityRequestManager sender, UserActivityRequestedEventArgs e)
        {
            using (e.GetDeferral())
            {
                // Generate a user activity that remembers the scroll position.
                var scrollViewer   = FindScrollViewer(ReaderElement);
                var scrollProgress = scrollViewer.ScrollableHeight > 0 ? scrollViewer.ContentVerticalOffset / scrollViewer.ScrollableHeight : 0.0;

                // Create user activity session for this window.
                var activityId = FormattableString.Invariant($"book?id={BookId}&pos={scrollProgress}");
                var activity   = new UserActivity(activityId);
                activity.ActivationUri = new Uri($"{App.ProtocolScheme}:{activityId}");
                activity.VisualElements.DisplayText = Book.Title;
                activity.VisualElements.Description = $"{(int)(scrollProgress * 100)}% complete";

                var card = new AdaptiveCard();
                card.BackgroundImage = Book.ImageUri;
                card.Body.Add(new AdaptiveTextBlock(Book.Title)
                {
                    Size = AdaptiveTextSize.Large, Weight = AdaptiveTextWeight.Bolder
                });
                activity.VisualElements.Content = AdaptiveCardBuilder.CreateAdaptiveCardFromJson(card.ToJson());

                e.Request.SetUserActivity(activity);
            }
        }
Exemplo n.º 7
0
        public async Task UpdateActivityAsync(ISource source, Media media, IEnumerable <Media> queue, string token, TimeSpan?timeSpan, bool isShuffled)
        {
            if (media.MediaType != MediaType.Track)
            {
                return;
            }
            var track = (Track)media;

            var activity = await _channel.GetOrCreateUserActivityAsync("last-playback");

            activity.FallbackUri = new Uri("https://soundbytemedia.com/pages/remote-subsystem");

            var continueText = @"Continue listening to " + track.Title.Replace('"', ' ') + " and " + queue.Count() + " other songs.";

            activity.VisualElements.DisplayText = track.Title.Replace('"', ' ');
            activity.VisualElements.Description = continueText;

            var json = @"{""$schema"":""http://adaptivecards.io/schemas/adaptive-card.json"",""type"":""AdaptiveCard"",""backgroundImage"":""" + track.ArtworkUrl + @""",""version"": ""1.0"",""body"":[{""type"":""Container"",""items"":[{""type"":""TextBlock"",""text"":""" + track.Title.Replace('"', ' ') + @""",""weight"":""bolder"",""size"":""large"",""wrap"":true,""maxLines"":3},{""type"":""TextBlock"",""text"":""" + continueText + @""",""size"":""default"",""wrap"":true,""maxLines"":3}]}]}";

            activity.VisualElements.Content = AdaptiveCardBuilder.CreateAdaptiveCardFromJson(json);

            activity.ActivationUri = new Uri("https://soundbytemedia.com/pages/remote-subsystem");

            await activity.SaveAsync();

            // Session
            await DispatcherHelper.ExecuteOnUIThreadAsync(() =>
            {
                _currentUserActivitySession?.Dispose();
                _currentUserActivitySession = null;

                _currentUserActivitySession = activity.CreateSession();
            });
        }
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            // Remember which trip we came from, so we can perform a connected animation.
            defaultId = e.Parameter as string;

            // Clear any trip title.
            ApplicationView.GetForCurrentView().Title = String.Empty;

            // Generate a UserActivity that says that
            // the user is looking at the trips overview.
            var    channel    = UserActivityChannel.GetDefault();
            string activityId = "home";
            var    activity   = await channel.GetOrCreateUserActivityAsync(activityId);

            // Describe the activity.
            activity.ActivationUri = new Uri($"{App.ProtocolScheme}:{activityId}");
            activity.VisualElements.DisplayText = "Trips Overview";

            var card = new AdaptiveCard();

            // Source: https://www.publicdomainpictures.net/en/view-image.php?image=248425
            card.BackgroundImageString = "https://www.publicdomainpictures.net/pictures/250000/velka/passport-a-map-and-money.jpg";
            card.Body.Add(new AdaptiveTextBlock("Trips Overview")
            {
                Size = AdaptiveTextSize.Large, Weight = AdaptiveTextWeight.Bolder
            });
            card.Body.Add(new AdaptiveTextBlock("2 trips"));
            activity.VisualElements.Content = AdaptiveCardBuilder.CreateAdaptiveCardFromJson(card.ToJson());

            // Save it to the channel.
            await activity.SaveAsync();

            // Start a session.
            activitySession = activity.CreateSession();
        }
Exemplo n.º 9
0
        public async void OnGetActivityClick(object sender, RoutedEventArgs e)
        {
            ActivityId = Guid.NewGuid().ToString();

            // Get or Create a activity
            var activity = await UserActivityChannel.GetDefault().GetOrCreateUserActivityAsync(ActivityId);

            // if you want to use Adaptive card, reference: https://docs.microsoft.com/en-us/adaptive-cards/create/gettingstarted
            activity.VisualElements.Content = AdaptiveCardBuilder.CreateAdaptiveCardFromJson(@"{
                                              ""$schema"": ""http://adaptivecards.io/schemas/adaptive-card.json"",
                                              ""type"": ""AdaptiveCard"",
                                              ""backgroundImage"": ""https://cdn2.ettoday.net/images/1376/d1376700.jpg"",
                                              ""version"": ""1.0"",
                                              ""body"" : [ {
                                                ""type"": ""Container"", 
                                                ""items"": [
                                                    {
                                                        ""type"": ""TextBlock"",
                                                        ""text"": ""from adaptive card"",
                                                        ""size"": ""large"",
                                                        ""wrap"": ""true"",
                                                        ""maxLines"": ""3""
                                                    }    
                                                ]
                                              } ]
                                              }");

            if (activity.State == UserActivityState.New)
            {
                // this is a new activity
                activity.VisualElements.DisplayText = "new activity";
                activity.ActivationUri = new Uri($"testapp://mainPage?state=new&id={ActivityId}");
            }
            else
            {
                // this is published activity
                activity.VisualElements.DisplayText = "published activity";
                activity.ActivationUri = new Uri($"testapp://mainPage?state=published&id={ActivityId}");
            }

            // set activity content info
            activity.ContentInfo = UserActivityContentInfo.FromJson(@"{
                ""user_id"": ""pou"",
                ""email"": ""*****@*****.**""
            }");

            // FallbackUri is handled when System invoke ActivationUri failed.
            //activity.FallbackUri = new Uri("https://dotblogs.com.tw/pou");

            activity.VisualElements.BackgroundColor = Color.FromArgb(0xFF, 0x88, 0x88, 0x88);

            await activity.SaveAsync();

            // a activity match an session, need close other sessions.
            activitySesion?.Dispose();
            activitySesion = activity.CreateSession();
        }
Exemplo n.º 10
0
        //时间线支持
        public static async Task GenerateActivityAsync(string DisplayText, AdaptiveCard Card, Uri ActivationUri, string ActivityID)
        {
            UserActivityChannel channel      = UserActivityChannel.GetDefault();
            UserActivity        userActivity = await channel.GetOrCreateUserActivityAsync(ActivityID);

            userActivity.VisualElements.DisplayText = DisplayText;
            userActivity.VisualElements.Content     = AdaptiveCardBuilder.CreateAdaptiveCardFromJson(Card.ToJson());
            userActivity.ActivationUri = ActivationUri;
            await userActivity.SaveAsync();

            _currentActivity?.Dispose();
            _currentActivity = userActivity.CreateSession();
        }
Exemplo n.º 11
0
    public async void Create(string json, string text)
    {
        string       id       = random.Next(1, 100000000).ToString();
        UserActivity activity = await channel.GetOrCreateUserActivityAsync(id);

        activity.VisualElements.DisplayText = text;
        activity.VisualElements.Content     =
            AdaptiveCardBuilder.CreateAdaptiveCardFromJson(json);
        activity.ActivationUri = new Uri(uri);
        activity.FallbackUri   = new Uri(uri);
        await activity.SaveAsync();

        UserActivitySession session = activity.CreateSession();

        session?.Dispose();
    }
Exemplo n.º 12
0
        public async Task AddCardToTimeline(FileViewModel card)
        {
            UserActivityChannel channel      = UserActivityChannel.GetDefault();
            UserActivity        userActivity = await channel.GetOrCreateUserActivityAsync(Guid.NewGuid().ToString());

            userActivity.VisualElements.DisplayText            = "Card error: " + card.Name;
            userActivity.VisualElements.AttributionDisplayText = card.Name;
            userActivity.ActivationUri = new Uri("https://github.com/Microsoft/AdaptiveCards/blob/master/samples/" + card.Name + ".json");

            userActivity.VisualElements.Content = AdaptiveCardBuilder.CreateAdaptiveCardFromJson(card.Contents);

            await userActivity.SaveAsync();

            _currentSession?.Dispose();
            _currentSession = userActivity.CreateSession();
        }
Exemplo n.º 13
0
        void OnUserActivityRequested(UserActivityRequestManager sender, UserActivityRequestedEventArgs e)
        {
            // The system raises the UserActivityRequested event to request that the
            // app generate an activity that describes what the user is doing right now.
            // This activity is used to restore the app as part of a Set.

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

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

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

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

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

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

                // Respond to the request.
                e.Request.SetUserActivity(activity);
            }
        }
        public async Task AddToTimeline(Expense expense)
        {
            _userActivityChannel = UserActivityChannel.GetDefault();
            _userActivity        = await _userActivityChannel.GetOrCreateUserActivityAsync($"Expense-{expense.ExpenseId}");

            _userActivity.ActivationUri = new Uri($"contosoexpenses://expense/{expense.ExpenseId}");
            _userActivity.VisualElements.DisplayText = "Contoso Expenses";

            string json = BuildAdaptiveCard(expense);

            _userActivity.VisualElements.Content = AdaptiveCardBuilder.CreateAdaptiveCardFromJson(json);

            await _userActivity.SaveAsync();

            _userActivitySession?.Dispose();
            _userActivitySession = _userActivity.CreateSession();
        }
Exemplo n.º 15
0
        private async void RenderResult_OnAction(RenderedAdaptiveCard sender, AdaptiveActionEventArgs e)
        {
            if (e.Action.ActionType == ActionType.OpenUrl)
            {
                _userActivity.ActivationUri = new Uri("adaptivecards://openLastPost");
                _userActivity.VisualElements.DisplayText = "Windows AppConsult blog";
                _userActivity.VisualElements.Content     = AdaptiveCardBuilder.CreateAdaptiveCardFromJson(json);

                await _userActivity.SaveAsync();

                _userActivitySession?.Dispose();
                _userActivitySession = _userActivity.CreateSession();

                var action = e.Action as AdaptiveOpenUrlAction;
                await Launcher.LaunchUriAsync(action.Url);
            }
        }
Exemplo n.º 16
0
        private async Task CreateActivityAsync(AppContent target)
        {
            var channel  = UserActivityChannel.TryGetForWebAccount(Account);
            var activity = await channel.GetOrCreateUserActivityAsync(target.Id);

            activity.ActivationUri = new Uri($"decodedemo:?id={target.Id}");

            var card = target.ToAdaptiveCard();

            activity.VisualElements.Content     = AdaptiveCardBuilder.CreateAdaptiveCardFromJson(card.ToJson());
            activity.VisualElements.DisplayText = target.Title;

            await activity.SaveAsync();

            _currentActivity?.Dispose();
            _currentActivity = activity.CreateSession();
        }
        public async void Insert(BrowsingHistory entity)
        {
            var userActivityChannel = UserActivityChannel.GetDefault();
            var model = await GetPixevalTimelineModel(entity);

            var userActivity = await userActivityChannel.GetOrCreateUserActivityAsync($"Pixeval-{model.Id}-{DateTime.Now:s}");

            userActivity.VisualElements.DisplayText            = model.Title;
            userActivity.VisualElements.Content                = AdaptiveCardBuilder.CreateAdaptiveCardFromJson(BuildAdaptiveCard(model));
            userActivity.VisualElements.Attribution            = new UserActivityAttribution(iconUri);
            userActivity.VisualElements.AttributionDisplayText = "Pixeval";
            userActivity.ActivationUri = new Uri(entity.Type switch
            {
                "illust" => $"pixeval://www.pixiv.net/artworks/{model.Id}",
                "user" => $"pixeval://www.pixiv.net/users/{model.Id}",
                "spotlight" => $"pixeval://www.pixivision.net/en/a/{model.Id}",
                _ => throw new ArgumentException(nameof(entity.Type))
            });
Exemplo n.º 18
0
        public async static void AddToTimeLine(Activity data)
        {
            UserActivityChannel Channel  = UserActivityChannel.GetDefault();
            UserActivity        Activity = await Channel.GetOrCreateUserActivityAsync(data.url);

            Activity.ActivationUri = new Uri("tencentvideo:video?url=" + data.url);
            Activity.VisualElements.DisplayText = "腾讯视频";
            StorageFile CardFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Data/activity.json"));

            string CardText = await FileIO.ReadTextAsync(CardFile);

            CardText = TransferTemplate(CardText);
            string ActivityContent = string.Format(CardText, data.image, data.title, data.description);

            Activity.VisualElements.Content = AdaptiveCardBuilder.CreateAdaptiveCardFromJson(ActivityContent);
            await Activity.SaveAsync();

            CurrentSession = Activity.CreateSession();
        }
Exemplo n.º 19
0
        private async void setMicrosoftTimeline(Status tw)
        {
            CreateAdaptiveCardForTimeline(tw);
            var programId = findProgramId(tw.Text);
            //タイムラインに追加する
            var userChannel  = UserActivityChannel.GetDefault();
            var userActivity = await userChannel.GetOrCreateUserActivityAsync($"NicoLiveAlert_TwitterCS_{programId}");

            //設定
            userActivity.VisualElements.DisplayText = $"番組が開始しました。\n{tw.Text}";
            userActivity.VisualElements.Content     = AdaptiveCardBuilder.CreateAdaptiveCardFromJson(card.ToJson());
            userActivity.ActivationUri = new Uri("https://live2.nicovideo.jp/watch/" + programId);

            //保存
            await userActivity.SaveAsync();

            _currentActivity?.Dispose();
            _currentActivity = userActivity.CreateSession();
        }
Exemplo n.º 20
0
        public async Task LogOrUpdateActivityAsync(IFile file)
        {
            using (await TimelineMutex.LockAsync())
            {
                // Load the template, if needed
                if (_Template is null)
                {
                    StorageFile templateFile = await StorageFile.GetFileFromApplicationUriAsync(TemplateUri);

                    _Template = await FileIO.ReadTextAsync(templateFile);
                }

                // Get a unique id for the file
                uint numericId = (uint)HashCode <char> .Combine(file.Path.AsSpan());

                string
                    textId     = numericId.ToString(),
                    preview    = await CodeLibraryEntry.LoadCodePreviewAsync(file),
                    background = BackgroundImages[(int)(numericId % BackgroundImages.Count)];

                // Create the model to represent the current activity
                AdaptiveCard model = new AdaptiveCard(file.DisplayName, preview, background);

                // Render the adaptive card
                string adaptiveCard = await StaticStubbleRenderer.Instance.RenderAsync(_Template, model);

                // Get the default channel and create the activity
                UserActivity activity = await UserActivityChannel.GetDefault().GetOrCreateUserActivityAsync(textId);

                // Set the deep-link and the title
                activity.ActivationUri = new Uri($"brainf-ck:///file?path={file.Path}");
                activity.VisualElements.DisplayText = file.DisplayName;
                activity.VisualElements.Content     = AdaptiveCardBuilder.CreateAdaptiveCardFromJson(adaptiveCard);
                activity.IsRoamable = false;

                // Save to activity feed.
                await activity.SaveAsync();

                // Update the activity currently in use
                _Session?.Dispose();
                _Session = activity.CreateSession();
            }
        }
Exemplo n.º 21
0
        private async void RenderResult_OnAction(RenderedAdaptiveCard sender, AdaptiveActionEventArgs e)
        {
            if (e.Action.Type == "Action.OpenUrl")
            {
                if (_desktopBridgeHelpers.IsRunningAsUwp())
                {
                    _userActivity.ActivationUri = new Uri("adaptivecards://openLastPost");
                    _userActivity.VisualElements.DisplayText = "Windows AppConsult blog";
                    _userActivity.VisualElements.Content     = AdaptiveCardBuilder.CreateAdaptiveCardFromJson(json);

                    await _userActivity.SaveAsync();

                    _userActivitySession?.Dispose();
                    _userActivitySession = _userActivity.CreateSession();
                }

                var action = e.Action as AdaptiveOpenUrlAction;
                Process.Start(action.Url.ToString());
            }
        }
Exemplo n.º 22
0
        private async void OnCreateActivity(object sender, RoutedEventArgs e)
        {
            string cardText = @"{
                ""type"": ""AdaptiveCard"",
                ""version"": ""1.0"",
                ""$schema"": ""http://adaptivecards.io/schemas/adaptive-card.json"",
                ""body"": [{
                    ""type"": ""TextBlock"",
                    ""horizontalAlignment"": ""Center"",
                    ""size"": ""Large"",
                    ""text"": ""Hello BASTA!""
                },
                {
                    ""type"": ""TextBlock"",
                    ""horizontalAlignment"": ""Left"",
                    ""size"": ""Small"",
                    ""text"": ""This is a sample for BASTA! 2019in Frankfurt"",
                    ""maxLines"": 3,
                    ""wrap"": true
                }]
            }";

            try
            {
                UserActivityChannel channel  = UserActivityChannel.GetDefault();
                UserActivity        activity = await channel.GetOrCreateUserActivityAsync("MainPage5");

                activity.VisualElements.DisplayText = "BASTA! Sample";
                activity.ActivationUri = new Uri("basta://MainPage/1");
                var card = AdaptiveCardBuilder.CreateAdaptiveCardFromJson(cardText);
                activity.VisualElements.Content = card;
                await activity.SaveAsync();

                _session?.Dispose();
                _session = activity.CreateSession();
            }
            catch (Exception ex)
            {
                new MessageDialog(ex.Message);
            }
        }
        private async void Window_SourceInitialized(object sender, EventArgs e)
        {
            windowHandle = (new System.Windows.Interop.WindowInteropHelper(this)).Handle;

            // Title bar colors.
            ApplicationViewTitleBar titleBar = ComInterop.GetTitleBarForWindow(windowHandle);

            if (titleBar != null)
            {
                titleBar.BackgroundColor = Color.FromArgb(255, 54, 60, 116);
                titleBar.ForegroundColor = Color.FromArgb(255, 232, 211, 162);
            }

            // Generate a UserActivity that says that
            // the user is looking at the library.
            var    channel    = UserActivityChannel.GetDefault();
            string activityId = "home";
            var    activity   = await channel.GetOrCreateUserActivityAsync(activityId);

            // Describe the activity.
            activity.ActivationUri = new Uri($"{App.ProtocolScheme}:{activityId}");
            activity.VisualElements.DisplayText = "Library";
            activity.VisualElements.Description = "4 books";

            var card = new AdaptiveCard();

            // Photo by Mikhail Pavstyuk (https://unsplash.com/photos/EKy2OTRPXdw) free for commercial use.
            card.BackgroundImage = new Uri("https://images.unsplash.com/photo-1423592707957-3b212afa6733");
            card.Body.Add(new AdaptiveTextBlock("Library")
            {
                Size = AdaptiveTextSize.Large, Weight = AdaptiveTextWeight.Bolder
            });
            card.Body.Add(new AdaptiveTextBlock("4 books"));
            activity.VisualElements.Content = AdaptiveCardBuilder.CreateAdaptiveCardFromJson(card.ToJson());

            // Save it to the channel.
            await activity.SaveAsync();

            // Start a session.
            session = activity.CreateSessionForWindow(windowHandle);
        }
Exemplo n.º 24
0
        private async Task GenerateActivityAsync()
        {
            //Get the default UserActivityChannel and query it for our UserActivity. If the activity doesn't exist, one is created.
            UserActivityChannel channel = UserActivityChannel.GetDefault();
            //The text here should be treated as a title for this activity and should be unique to this app.
            UserActivity userActivity = await channel.GetOrCreateUserActivityAsync("APOD-UWP");

            //Populate required properties: DisplayText and ActivationUri are required.
            userActivity.VisualElements.DisplayText = "APOD-UWP TIMELINE ACTIVITIES";
            userActivity.ActivationUri = new Uri("proto://");
            //Build the adaptive card from a JSON string.
            userActivity.VisualElements.Content = AdaptiveCardBuilder.CreateAdaptiveCardFromJson(apodTimelineCard.ToJson());
            //Set the mime type of the user activity, in this case, an application.
            userActivity.ContentType = "application.octet-stream";
            //Save the new metadata.
            await userActivity.SaveAsync();

            //Dispose of any current UserActivitySession, and create a new one.
            _currentActivity?.Dispose();
            _currentActivity = userActivity.CreateSession();
        }
Exemplo n.º 25
0
        // TODO WTS: Change this to configure your own adaptive card
        // For more info about adaptive cards see http://adaptivecards.io/
        private static IAdaptiveCard CreateAdaptiveCardSample(string displayText, string description, string imageUrl)
        {
            var adaptiveCard = new AdaptiveCard("1.0");
            var columns      = new AdaptiveColumnSet();
            var firstColumn  = new AdaptiveColumn()
            {
                Width = "auto"
            };
            var secondColumn = new AdaptiveColumn()
            {
                Width = "*"
            };

            firstColumn.Items.Add(new AdaptiveImage()
            {
                Url  = new Uri(imageUrl),
                Size = AdaptiveImageSize.Medium
            });

            secondColumn.Items.Add(new AdaptiveTextBlock()
            {
                Text   = displayText,
                Weight = AdaptiveTextWeight.Bolder,
                Size   = AdaptiveTextSize.Large
            });

            secondColumn.Items.Add(new AdaptiveTextBlock()
            {
                Text   = description,
                Size   = AdaptiveTextSize.Medium,
                Weight = AdaptiveTextWeight.Lighter,
                Wrap   = true
            });

            columns.Columns.Add(firstColumn);
            columns.Columns.Add(secondColumn);
            adaptiveCard.Body.Add(columns);

            return(AdaptiveCardBuilder.CreateAdaptiveCardFromJson(adaptiveCard.ToJson()));
        }
Exemplo n.º 26
0
        public async Task <UserActivity> UpdateActivityAsync(ISource source, BaseTrack track, IEnumerable <BaseSoundByteItem> playlist, string token, TimeSpan?timeSpan, bool isShuffled)
        {
            // Don't enable if windows timeline support is disabled
            if (!SettingsService.Instance.WindowsTimelineEnabled)
            {
                return(null);
            }

            // We do not support these items
            if (track.ServiceType == ServiceTypes.ITunesPodcast ||
                track.ServiceType == ServiceTypes.Local ||
                track.ServiceType == ServiceTypes.Unknown)
            {
                return(null);
            }

            var activity = await _channel.GetOrCreateUserActivityAsync("playback-" + SettingsService.Instance.SessionId);

            activity.FallbackUri = new Uri("https://soundbytemedia.com/pages/remote-subsystem");

            var continueText = @"Continue listening to " + track.Title.Replace('"', ' ') + " and " + playlist.Count() + " other songs.";

            activity.VisualElements.DisplayText = track.Title.Replace('"', ' ');
            activity.VisualElements.Description = continueText;

            var json = @"{""$schema"":""http://adaptivecards.io/schemas/adaptive-card.json"",""type"":""AdaptiveCard"",""backgroundImage"":""" + track.ArtworkUrl + @""",""version"": ""1.0"",""body"":[{""type"":""Container"",""items"":[{""type"":""TextBlock"",""text"":""" + track.Title.Replace('"', ' ') + @""",""weight"":""bolder"",""size"":""large"",""wrap"":true,""maxLines"":3},{""type"":""TextBlock"",""text"":""" + continueText + @""",""size"":""default"",""wrap"":true,""maxLines"":3}]}]}";

            activity.VisualElements.Content = AdaptiveCardBuilder.CreateAdaptiveCardFromJson(json);

            // Set the activation url using shorthand protocol
            var protoUri = ProtocolHelper.EncodeTrackProtocolItem(new ProtocolHelper.TrackProtocolItem(source, new BaseSoundByteItem(track), playlist, token, timeSpan, isShuffled), true) + "&session=" + SettingsService.Instance.SessionId;

            activity.ActivationUri = new Uri(protoUri);

            await activity.SaveAsync();

            return(activity);
        }
Exemplo n.º 27
0
        /// <summary>
        /// 生成时间线卡片
        /// </summary>
        /// <param name="feed"></param>
        /// <returns></returns>
        private async Task GenerateActivityAsync(RssSchema feed)
        {
            try
            {
                UserActivityChannel channel      = UserActivityChannel.GetDefault();
                UserActivity        userActivity = await channel.GetOrCreateUserActivityAsync(feed.InternalID);

                userActivity.VisualElements.DisplayText = feed.Title;
                userActivity.VisualElements.Content     = AdaptiveCardBuilder.CreateAdaptiveCardFromJson(await AppTools.CreateAdaptiveJson(feed));
                //Populate required properties
                string url = $"richasy-rss://feed?id={WebUtility.UrlEncode(feed.InternalID)}&summary={WebUtility.UrlEncode(feed.Summary)}&date={WebUtility.UrlEncode(feed.PublishDate.ToString())}&img={WebUtility.UrlEncode(feed.ImageUrl)}&url={WebUtility.UrlDecode(feed.FeedUrl)}&title={WebUtility.UrlEncode(feed.Title)}&content={WebUtility.UrlEncode(feed.Content)}";
                userActivity.ActivationUri = new Uri(url);
                await userActivity.SaveAsync(); //save the new metadata

                //Dispose of any current UserActivitySession, and create a new one.
                _currentActivity?.Dispose();
                _currentActivity = userActivity.CreateSession();
            }
            catch (Exception)
            {
                return;
            }
        }
Exemplo n.º 28
0
        private async Task CreateAdaptiveCardForTimelineAsync()
        {
            // Fetch the adaptive card JSON.
            var adaptiveCard = File.ReadAllText(
                $@"{Package.Current.InstalledLocation.Path}\AdaptiveCards\timeline.json");

            // Create the protocol, so when the clicks the Adaptive Card on the Timeline,
            // it will directly launch to the correct image.
            _userActivity.ActivationUri = new Uri("contoso-insurance://case?#1703542");

            // Set the display text to the User Activity.
            _userActivity.VisualElements.DisplayText = "NEW CASE";

            // Assign the Adaptive Card to the user activity.
            _userActivity.VisualElements.Content =
                AdaptiveCardBuilder.CreateAdaptiveCardFromJson(adaptiveCard);

            // Save the details user activity.
            await _userActivity.SaveAsync();

            // Dispose of the session and create a new one ready for the next activity.
            _userActivitySession?.Dispose();
            _userActivitySession = _userActivity.CreateSession();
        }
        private async Task CreateUserActivityAsync()
        {
            // Get channel and create activity.
            UserActivityChannel channel  = UserActivityChannel.GetDefault();
            UserActivity        activity = await channel.GetOrCreateUserActivityAsync("Scenario3_AdaptiveCard");

            // Set deep-link and properties.
            activity.ActivationUri = new Uri("sdkUserActivitySample:page?Scenario3_AdaptiveCard");
            activity.VisualElements.DisplayText = "User Activity with Adaptive Card";

            // Sreate and set Adaptive Card.
            StorageFile cardFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/UserActivityCard.json"));

            string cardText = await FileIO.ReadTextAsync(cardFile);

            activity.VisualElements.Content = AdaptiveCardBuilder.CreateAdaptiveCardFromJson(cardText);

            // Save to activity feed.
            await activity.SaveAsync();

            // Create a session, which indicates that the user is engaged
            // in the activity.
            _currentSession = activity.CreateSession();
        }
Exemplo n.º 30
0
        public static async Task GenerateActivityAsync(string ChannelId, string ChannelName, string Image)
        {
            channel      = UserActivityChannel.GetDefault();
            userActivity = await channel.GetOrCreateUserActivityAsync(ChannelId);

            //Populate required properties
            timelinecard = timelinecard.Replace("$TITLE", ChannelName);
            timelinecard = timelinecard.Replace("$SUBTITLE", "");

            if (Image != null)
            {
                timelinecard = timelinecard.Replace("$IMAGE", Image);
            }

            userActivity.VisualElements.Content     = AdaptiveCardBuilder.CreateAdaptiveCardFromJson(timelinecard);
            userActivity.VisualElements.DisplayText = "Hello Activities";

            userActivity.ActivationUri = new Uri("quarrel://channels/@me/" + ChannelId);
            if (Image != null)
            {
                userActivity.ContentUri = new Uri(Image);
            }
            userActivity.ContentInfo = UserActivityContentInfo.FromJson("{\"@context\":\"~~http~~://schema.org\",\"@type\": \"CommunicateAction\",\"subjectOf\": \"" + ChannelName + "\"}");
            userActivity.FallbackUri = new Uri("http://discordapp.com/channels/@me/" + ChannelId);


            //Save
            await userActivity.SaveAsync(); //save the new metadata

            _currentActivity?.Dispose();
            await App.dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                          () =>
            {
                _currentActivity = userActivity.CreateSession();
            });
        }