예제 #1
0
        public async void Insert(BrowsingHistory browsingHistory)
        {
            var userActivityChannel = UserActivityChannel.GetDefault();
            var model = await GetPixevalTimelineModel(browsingHistory);

            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(browsingHistory.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(browsingHistory.Type))
            });
예제 #2
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());
            }
        }
예제 #3
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);
        }
        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();
        }
예제 #6
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()));
        }
예제 #7
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);
        }
예제 #8
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;
            }
        }
예제 #9
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();
            });
        }
예제 #10
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();
        }
예제 #12
0
        public async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> argument)
        {
            try
            {
                var message          = await argument;
                var incomingActivity = (message as Activity);
                LastSeenActivity = incomingActivity;

                var teamsFlowbotManager = new TeamsFlowbotManager(
                    processSimpleConfiguration: ProcessSimpleConfiguration.Instance,
                    httpConfiguration: GlobalConfiguration.Configuration,
                    withUnencryptedFlowbotPassword: true);

                var sendingAccount        = incomingActivity.From.ToBotChannelAccount();
                var responderUserIdentity = new UserIdentity {
                    ObjectId = incomingActivity.From.AadObjectId, UserPrincipalName = sendingAccount.Id
                };

                if (message.Text == null)
                {
                    // Current flowSvc code is case sensitive on this, and its incoming capitalization from emulator is now lowercase:
                    var adaptiveActionData = AdaptiveActionData.Deserialize(JToken.Parse(incomingActivity.Value.ToString().Replace("actionType", "ActionType")));

                    await teamsFlowbotManager.ReceiveAdaptiveAction(
                        adaptiveActionData : adaptiveActionData,
                        replyActivity : incomingActivity.CreateReply().ToBotActivity(),
                        sendingAccount : sendingAccount,
                        responderUserIdentity : responderUserIdentity,
                        idOfActivityFromWhichTheActionWasEmitted : null, // the method won't use this since we're supplying it with our own post method
                        cancellationToken : new CancellationTokenSource().Token,
                        asyncPostActivity : (botActivity) => {
                        if (incomingActivity.ServiceUrl.StartsWith("http://localhost"))
                        {
                            // Message update appears to be broken in emulator: incomingActivity.ReplyToId is null, and even if we use the value it
                            // should have, it doesn't work. Does not help to set id and replyToId on botActivity to match those of the message we're
                            // updating. So for now, in emulator we post rather than updating.
                            return(new ConnectorClient(new Uri(incomingActivity.ServiceUrl))
                                   .Conversations
                                   .ReplyToActivityAsync(incomingActivity.Conversation.Id, incomingActivity.Id, botActivity.ToActivity()));
                        }
                        else
                        {
                            return(new ConnectorClient(new Uri(incomingActivity.ServiceUrl))
                                   .Conversations
                                   .UpdateActivityAsync(incomingActivity.Conversation.Id, incomingActivity.ReplyToId, botActivity.ToActivity()));
                        }
                    }
                        );

                    context.Wait(MessageReceivedAsync);
                }
                else
                {
                    var trimmedText = new Regex("<at>[a-zA-Z]+</at>").Replace(message.Text, "").Trim();

                    if (trimmedText == "reset")
                    {
                        PromptDialog.Confirm(
                            context,
                            AfterResetAsync,
                            "Are you sure you want to reset the count?",
                            "Didn't get that!",
                            promptStyle: PromptStyle.Auto);
                    }
                    else if (trimmedText.StartsWith("lookup"))
                    {
                        var    teamId      = trimmedText.Replace("lookup", "").Trim();
                        string appId       = "087f000e-5e1c-4114-b991-6cc0845783d9";
                        string appPassword = "******";
                        string scope       = "https://api.botframework.com/.default";

                        var queryParams = new KeyValuePair <string, string>[]
                        {
                            new KeyValuePair <string, string>("grant_type", "client_credentials"),
                            new KeyValuePair <string, string>("client_id", appId),
                            new KeyValuePair <string, string>("client_secret", appPassword),
                            new KeyValuePair <string, string>("scope", scope)
                        };

                        using (var httpClient = new HttpClient())
                        {
                            HttpResponseMessage response;
                            string token;
                            string teamDetailsRequestUrl = $"{message.ServiceUrl}v3/teams/{teamId}";

                            using (var tokenRequestContent = new FormUrlEncodedContent(queryParams))
                            {
                                string tokenUrl         = "https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token";
                                string tokenContentType = "application/x-www-form-urlencoded";
                                tokenRequestContent.Headers.Clear();
                                tokenRequestContent.Headers.Add("Content-Type", tokenContentType);
                                response = await httpClient.PostAsync(tokenUrl, tokenRequestContent);

                                var responseContent = await response.Content.ReadAsStringAsync();

                                token = JsonConvert.DeserializeObject <JObject>(responseContent)["access_token"].ToString();
                            }

                            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
                            response = await httpClient.GetAsync(teamDetailsRequestUrl);

                            await context.PostAsync($"Details for team {teamId}: {response.Content.ReadAsStringAsync().Result}");

                            context.Wait(MessageReceivedAsync);
                        }
                    }
                    else if (trimmedText.StartsWith("notification"))
                    {
                        var notification         = trimmedText.Substring("notification".Length).Trim();
                        var notificationSegments = notification.Split(';').ToList();

                        var notificationRequestData = new BotNotificationRequest <UserBotRecipient>
                        {
                            Recipient = new UserBotRecipient {
                                To = incomingActivity.From.Name
                            },
                            MessageTitle = PopFrom(notificationSegments),
                            MessageBody  = PopFrom(notificationSegments)
                        };

                        // todo: split up recipients array and look them up in graph
                        var adaptiveCard = AdaptiveCardBuilder.BuildNotificationCard(
                            cultureInfo: CultureInfo.CurrentCulture,
                            requestor: new RequestIdentity {
                            Name = (notificationRequestData.Recipient as UserBotRecipient).To
                        },
                            notificationTitle: notificationRequestData.MessageTitle,
                            notificationBody: notificationRequestData.MessageBody);

                        // await context.PostAsync(incomingActivity.CreateReply("You have been issued the following notification").ToBotActivity().WithAttachment(adaptiveCard).ToActivity());
                        var messageWithFooter = string.Format(
                            CultureInfo.InvariantCulture,
                            "{0}\r\n\r\n**{1}**",
                            notificationRequestData.MessageBody,
                            AdaptiveCardBuilder.GetFooterFromRequestor(
                                new RequestIdentity
                        {
                            Name = (notificationRequestData.Recipient as UserBotRecipient).To         //,
                                   // Claims = new Dictionary<string, string> { { "upn", "*****@*****.**" } }
                        }));

                        await context.PostAsync(incomingActivity.CreateReply(messageWithFooter));

                        context.Wait(MessageReceivedAsync);
                    }
                    else if (trimmedText.StartsWith("choice"))
                    {
                        var choice         = trimmedText.Substring("choice".Length).Trim();
                        var choiceSegments = choice.Split(';').ToList();
                        var options        = new[] { "option 1", "option 2", "option 3" };

                        var messageWithOptionsRequestData = new BotMessageWithOptionsRequest <UserBotRecipient>
                        {
                            Recipient = new UserBotRecipient {
                                To = incomingActivity.From.Name
                            },
                            MessageTitle = PopFrom(choiceSegments),
                            MessageBody  = PopFrom(choiceSegments),
                            Options      = options
                        };

                        // todo: split up recipients array and look them up in graph
                        var adaptiveCard = AdaptiveCardBuilder.BuildMessageWithOptionsRequestCard(
                            cultureInfo: CultureInfo.CurrentCulture,
                            choiceTitle: messageWithOptionsRequestData.MessageTitle,
                            choiceCreationDate: DateTime.Now,
                            requestor: new RequestIdentity {
                            Name = messageWithOptionsRequestData.Recipient.To, Claims = new Dictionary <string, string> {
                                { "upn", "*****@*****.**" }
                            }
                        },
                            choiceDetails: messageWithOptionsRequestData.MessageBody,
                            choiceOptions: messageWithOptionsRequestData.Options,
                            notificationUrl: null);

                        await context.PostAsync(incomingActivity.CreateReply("Your choice has been requested for the following item").ToBotActivity().WithAttachment(adaptiveCard).ToActivity());

                        context.Wait(MessageReceivedAsync);
                    }
                    else if (trimmedText.StartsWith("approval"))
                    {
                        var environment      = Guid.NewGuid().ToString();
                        var approvalName     = Guid.NewGuid().ToString();
                        var approvalLink     = "http://linkToApproval/inFlowPortal.com";
                        var approval         = trimmedText.Substring("approval".Length).Trim();
                        var approvalSegments = approval.Split(';').ToList();
                        var approvalOptions  = new[] { "option 1", "option 2", "option 3" };

                        var approvalTitle               = PopFrom(approvalSegments);
                        var approvalDetails             = PopFrom(approvalSegments);
                        var approvalItemLinkDescription = PopFrom(approvalSegments);
                        var approvalItemLink            = PopFrom(approvalSegments);

                        var approvalCreationDate = DateTime.Now.AddHours(-1);
                        var cultureInfo          = CultureInfo.CurrentCulture;

                        var adaptiveCard = AdaptiveCardBuilder.BuildApprovalRequestCard(
                            cultureInfo: cultureInfo,
                            approvalTitle: approvalTitle,
                            approvalCreationDate: approvalCreationDate,
                            requestor: new RequestIdentity {
                            Name = incomingActivity.From.Name, Claims = new Dictionary <string, string> {
                                { "upn", "*****@*****.**" }
                            }
                        },
                            approvalDetails: approvalDetails,
                            environment: environment,
                            approvalLink: approvalLink,
                            approvalName: approvalName,
                            approvalOptions: approvalOptions,
                            itemLink: approvalItemLink,
                            itemLinkDescription: approvalItemLinkDescription,
                            onBehalfOfNotice: "The OnBehalfOf Notice!!!");

                        var replyActivity = incomingActivity.CreateReply("Your approval has been requested for the following item");
                        await context.PostAsync(replyActivity.ToBotActivity().WithAttachment(adaptiveCard).ToActivity());

                        context.Wait(MessageReceivedAsync);
                    }
                    else if (trimmedText.StartsWith("html"))
                    {
                        var replyActivity = incomingActivity.CreateReply("<b>This is bold</b>And this is not <a href=\"https://www.google.com\">link</a>");
                        replyActivity.TextFormat = "html";
                        await context.PostAsync(replyActivity);

                        context.Wait(MessageReceivedAsync);
                    }
                    else if (trimmedText.StartsWith("mention"))
                    {
                        var text          = trimmedText.Substring("mention".Length).Trim();
                        var mentions      = incomingActivity.GetMentions();
                        var replyActivity = incomingActivity.CreateReply(string.Format("Your text contained {0} mentions. Here is a mention for you: ", mentions.Length));

                        // (this is actually Vincent)
                        var mention = new ChannelAccount(
                            id: "29:1P42CnPU5FKEBUXSfFX0pQS-yvsggkTHkNkpfnMisIfnI1X84UJo25DoffCfECYCnJG6Q8TC6wEQC04W7G4fMSQ",
                            name: "Baz Bing");

                        replyActivity = replyActivity.AddMentionToText(mention, MentionTextLocation.AppendText, "Foo Bar");

                        var card = AdaptiveCardBuilder.BuildNotificationCard(
                            CultureInfo.CurrentCulture,
                            new RequestIdentity {
                            Name = incomingActivity.From.Name, Claims = new Dictionary <string, string> {
                                { "upn", "*****@*****.**" }
                            }
                        },
                            "Here's a notification",
                            "and this is it's body which contains this mention which won't work because mentions aren't supported in cards: <at>Foo Bar</at>. the end.");

                        await context.PostAsync(replyActivity.WithAttachment(card));

                        context.Wait(MessageReceivedAsync);
                    }
                    else
                    {
                        await context.PostAsync($"{this.count++}: I say you said {message.Text}");

                        context.Wait(MessageReceivedAsync);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.Write(ex.ToString());
            }
        }
예제 #13
0
        private async Task CreateActivityAsync(BookData book, BookLocation location, string imageDataUrl)
        {
            if (!ProjectRomeEnabled)
            {
                return;
            }
            var channel  = UserActivityChannel.GetDefault();
            var activity = await channel.GetOrCreateUserActivityAsync(book.BookId);

            activity.VisualElements.DisplayText = $"Reading {book.Title}";
            activity.ActivationUri = AsUri(book.BookId, location);

            var title       = Windows.Data.Json.JsonValue.CreateStringValue(book.Title).Stringify();
            var authorvalue = book.BestAuthorDefaultIsNull;
            var author      = authorvalue == null ? "\"\"" : Windows.Data.Json.JsonValue.CreateStringValue("By " + authorvalue).Stringify();

            var reviewvalue = book?.Review?.Review;
            var review      = reviewvalue == null ? "\"\"" : Windows.Data.Json.JsonValue.CreateStringValue(reviewvalue).Stringify();

            var cardJson =
                @"{
	""$schema"": ""http://adaptivecards.io/schemas/adaptive-card.json"", 
	""type"": ""AdaptiveCard"", 
	""version"": ""1.0"",
	""body"": [
		{
			""type"": ""Container"", 
			""items"": [
				{
					""type"":""ColumnSet"",
					""columns"":[
						{
							""type"":""Column"",
							""width"":""auto"",
							""items"":[
								{
									""type"": ""Image"", 
									""url"": """                                     + imageDataUrl + @""", 
									""size"": ""large""
								}
							]
						},
						{
							""type"":""Column"",
							""width"":""auto"",
							""items"":[
								{
									""type"": ""TextBlock"", 
									""text"": "                                     + title + @", 
									""weight"": ""bolder"", 
									""size"": ""large"", 
									""wrap"": true
								},
								{
									""type"": ""TextBlock"", 
									""text"": "                                     + author + @", 
									""spacing"": ""none"", 
									""isSubtle"": true, 
									""wrap"": true 
								},
								{
									""type"": ""TextBlock"", 
									""text"": "                                     + review + @", 
									""spacing"": ""none"", 
									""wrap"": true 
								}
							]
						}
					]
				}
			]
		}
	]
}";
            var card = AdaptiveCardBuilder.CreateAdaptiveCardFromJson(cardJson);

            activity.VisualElements.Content = card;

            await activity.SaveAsync();

            var session = activity.CreateSession();

            if (Sessions.ContainsKey(book.BookId))
            {
                Sessions[book.BookId] = session;
            }
            else
            {
                Sessions.Add(book.BookId, session);
            }
        }
예제 #14
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);
        }
예제 #15
0
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            // Handle the events from the Back button, but do not show it.
            systemNavigationManager = SystemNavigationManager.GetForCurrentView();
            systemNavigationManager.BackRequested += OnBackRequested;

            // Parse the URI query parameters. They tell us what to load.
            var decoder = new WwwFormUrlDecoder((string)e.Parameter);

            Trip = TripData.FromId(GetDecoderField(decoder, "id"));
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Trip"));

            if (Trip == null)
            {
                // Invalid trip.
                return;
            }

            if (!int.TryParse(GetDecoderField(decoder, "todo"), out previousSelectedIndex))
            {
                previousSelectedIndex = -1;
            }

            // If applicable, perform a connected animation to make the page transition smoother.
            var animationService = ConnectedAnimationService.GetForCurrentView();
            var animation        = animationService.GetAnimation("drillin");

            if (animation != null)
            {
                animation.TryStart(HeroGrid);
            }

            // Update the title of the view to match the trip the user is looking at.
            ApplicationView.GetForCurrentView().Title = Trip.Title;

            // Generate a UserActivity that says that the user is looking at this trip.
            var    channel    = UserActivityChannel.GetDefault();
            string activityId = $"trip?id={Trip.Id}";
            var    activity   = await channel.GetOrCreateUserActivityAsync(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 = Trip.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(Trip.Description));
            var adaptiveCardJson = card.ToJson();

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

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

            // Start a session. This tels the system know that the user is engaged in the activity right now.
            this.activitySession = activity.CreateSession();

            // Subscribe to the UserActivityRequested event if the system supports it.
            if (ApiInformation.IsEventPresent(typeof(UserActivityRequestManager).FullName, "UserActivityRequested"))
            {
                activityRequestManager = UserActivityRequestManager.GetForCurrentView();
                activityRequestManager.UserActivityRequested += OnUserActivityRequested;
            }
        }
        private async void Window_SourceInitialized(object sender, EventArgs e)
        {
            Title = Book.Title;

            var scrollViewer = FindScrollViewer(ReaderElement);

            scrollViewer.ScrollToVerticalOffset(PreviousScrollProgress * scrollViewer.ScrollableHeight);

            var windowHandle = (new System.Windows.Interop.WindowInteropHelper(this)).Handle;

            // Set custom tab 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);
            }

            // Apply grouping behavior.
            if (!WantsCustomGroupingBehavior)
            {
                // Allow caller-specified default grouping to happen.
            }
            else if (AssociatedWindow == IntPtr.Zero)
            {
                // Open in new group.
                int preference = DWMTGP_NEW_TAB_GROUP;
                DwmSetWindowAttribute(windowHandle, DWMWA_TAB_GROUPING_PREFERENCE, ref preference, Marshal.SizeOf <int>());
            }
            else
            {
                // Join an existing group.
                int preference = DWMTGP_TAB_WITH_ASSOCIATED_WINDOW;
                DwmSetWindowAttribute(windowHandle, DWMWA_TAB_GROUPING_PREFERENCE, ref preference, Marshal.SizeOf <int>());

                DwmSetWindowAttribute(windowHandle, DWMWA_ASSOCIATED_WINDOW, ref AssociatedWindow, IntPtr.Size);
            }

            // Generate a UserActivity that says that
            // the user is reading this book.
            var channel  = UserActivityChannel.GetDefault();
            var activity = await channel.GetOrCreateUserActivityAsync(BookId);

            activity.ActivationUri = new Uri($"{App.ProtocolScheme}:{BookId}");
            activity.VisualElements.DisplayText = Book.Title;

            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());

            await activity.SaveAsync();

            Session = activity.CreateSessionForWindow(windowHandle);

            // Listen for user activity requests.
            userActivityRequestManager = ComInterop.GetUserActivityRequestManagerForWindow(windowHandle);
            if (userActivityRequestManager != null)
            {
                userActivityRequestManager.UserActivityRequested += OnUserActivityRequested;
            }
        }