public static async Task GetUserAsync(ITurnContext turnContext, TokenResponse tokenResponse, string upn)
        {
            if (turnContext == null)
            {
                throw new ArgumentNullException(nameof(turnContext));
            }

            if (tokenResponse == null)
            {
                throw new ArgumentNullException(nameof(tokenResponse));
            }

            var client = new SimpleGraphClient(tokenResponse.Token);
            var user   = await client.GetUserAsync(upn);

            var fileRead = System.IO.File.ReadAllText(@".\Resources\GetUserCard.json");
            var item     = (JObject)JsonConvert.DeserializeObject(fileRead);

            string classData = JsonConvert.SerializeObject(user, Formatting.Indented);

            AdaptiveTransformer transformer = new AdaptiveTransformer();
            string cardJson = transformer.Transform(fileRead, classData);

            Attachment attachment = new Attachment();

            attachment.ContentType = "application/vnd.microsoft.card.adaptive";
            attachment.Content     = JsonConvert.DeserializeObject(cardJson);

            var attachments = new List <Attachment>();
            var reply       = MessageFactory.Attachment(attachments);

            reply.Attachments.Add(attachment);

            await turnContext.SendActivityAsync(reply);
        }
Beispiel #2
0
        private async Task <DialogTurnResult> LoginStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            // Get the token from the previous step. Note that we could also have gotten the
            // token directly from the prompt itself. There is an example of this in the next method.
            var tokenResponse = (TokenResponse)stepContext.Result;

            if (tokenResponse?.Token != null)
            {
                // Pull in the data from the Microsoft Graph.
                var client = new SimpleGraphClient(tokenResponse.Token);
                var me     = await client.GetMeAsync();

                var title = !string.IsNullOrEmpty(me.JobTitle) ?
                            me.JobTitle : "Unknown";

                await stepContext.Context.SendActivityAsync($"You're logged in as {me.DisplayName} your token {tokenResponse.Token} ({me.UserPrincipalName}); you job title is: {title}");



                return(await stepContext.PromptAsync(nameof(ConfirmPrompt), new PromptOptions { Prompt = MessageFactory.Text("Would you like to register your app?") }, cancellationToken));
            }

            await stepContext.Context.SendActivityAsync(MessageFactory.Text("Login was not successful please try again."), cancellationToken);

            return(await stepContext.EndDialogAsync(cancellationToken : cancellationToken));
        }
        private async Task <DialogTurnResult> LoginStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            // Get the token from the previous step. Note that we could also have gotten the
            // token directly from the prompt itself. There is an example of this in the next method.
            var tokenResponse = (TokenResponse)stepContext.Result;

            if (tokenResponse?.Token != null)
            {
                // Pull in the data from the Microsoft Graph.
                var client = new SimpleGraphClient(tokenResponse.Token);
                var me     = await client.GetMyProfile();

                var imagelink = await client.GetPhotoAsync();

                var heroCard = new ThumbnailCard
                {
                    Title  = "Thumbnail Card",
                    Text   = $"Hello, {me.DisplayName}",
                    Images = new List <CardImage> {
                        new CardImage(imagelink)
                    },
                };
                var attachments = new Attachment(HeroCard.ContentType, null, heroCard);
                await stepContext.Context.SendActivityAsync(MessageFactory.Attachment(attachments), cancellationToken);

                return(await stepContext.PromptAsync(nameof(ConfirmPrompt), new PromptOptions { Prompt = MessageFactory.Text("Would you like to view your token?") }, cancellationToken));
            }
            await stepContext.Context.SendActivityAsync(MessageFactory.Text("Login was not successful please try again."), cancellationToken);

            return(await stepContext.EndDialogAsync(cancellationToken : cancellationToken));
        }
Beispiel #4
0
        private async Task <DialogTurnResult> CreateNewAppAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var tokenResponse = (TokenResponse)stepContext.Result;

            if (tokenResponse != null)
            {
                var client = new SimpleGraphClient(tokenResponse.Token);
                try
                {
                    var appBot = await client.RegisterNewApp("FAQPlusBotTest", "AzureADMultipleOrgs");

                    var secretsAppBot = await client.CreateNewPassword(appBot.Id);

                    var appConfig = await client.RegisterNewApp("FAQPlusConfigTest", "AzureADMyOrg");

                    var secretsAppConfig = await client.CreateNewPassword(appConfig.Id);

                    await stepContext.Context.SendActivityAsync($"Your app id is: {appBot.AppId}");
                }
                catch (System.Exception)
                {
                    throw;
                }
            }

            return(await stepContext.EndDialogAsync(cancellationToken : cancellationToken));
        }
Beispiel #5
0
        private async Task <DialogTurnResult> CreateAppointmentStepAsync(
            WaterfallStepContext stepContext,
            CancellationToken cancellationToken)
        {
            stepContext.Values["endTime"] = (string)stepContext.Result;

            var tokenResponse = stepContext.Options as TokenResponse;
            var start         = new DateTimeTimeZone
            {
                DateTime = (string)stepContext.Values["startTime"],
                TimeZone = "Pacific Standard Time"
            };

            var end = new DateTimeTimeZone
            {
                DateTime = (string)stepContext.Values["endTime"],
                TimeZone = "Pacific Standard Time"
            };

            var title = (string)stepContext.Values["title"];
            await SimpleGraphClient.GetAuthenticatedClient(tokenResponse.Token).SetAppointment(title, start, end);

            await stepContext.Context.SendActivityAsync("Event created",
                                                        cancellationToken : cancellationToken);

            return(await stepContext.EndDialogAsync());
        }
Beispiel #6
0
        private async Task <DialogTurnResult> AskForDuration(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            string result = (string)stepContext.Context.TurnState["data"]; //gets attendees' names

            var tokenResponse = (TokenResponse)stepContext.Result;         //gets token

            if (tokenResponse?.Token != null)
            {
                var      client        = new SimpleGraphClient(tokenResponse.Token);
                string[] attendeeNames = string.Concat(result.Where(c => !char.IsWhiteSpace(c))).Split(","); //splits comma separated names of attendees

                List <string> attendeeTableStorage = new List <string>();
                foreach (string name in attendeeNames)
                {
                    List <string> attendeeEmails = await client.GetAttendeeEmailFromName(name); //gets email from attendee's name

                    if (attendeeEmails.Count > 1)                                               //there can be multiple people having same first name, ask user to start again and enter email instead to be more specific
                    {
                        await stepContext.Context.SendActivityAsync("There are " + attendeeEmails.Count + " people whose name start with " + name + ". Please type hi to start again, and instead of first name, enter email to avoid ambiguity.");

                        return(await stepContext.EndDialogAsync(cancellationToken : cancellationToken));
                    }
                    else if (attendeeEmails.Count == 1)  // attendee found
                    {
                        attendeeTableStorage.Add(attendeeEmails[0]);
                    }
                    else //attendee not found in organization
                    {
                        await stepContext.Context.SendActivityAsync("Attendee not found, please type anything to start again");

                        return(await stepContext.EndDialogAsync(cancellationToken : cancellationToken));
                    }
                }

                var sb = new System.Text.StringBuilder();
                foreach (string email in attendeeTableStorage)
                {
                    sb.Append(email + ","); //converts emails to comma separated string to store in table
                }
                string finalString = sb.ToString().Remove(sb.Length - 1);
                if (result != null)
                {
                    MeetingDetail meetingDetail = new MeetingDetail(stepContext.Context.Activity.Conversation.Id, userEmail);
                    meetingDetail.Attendees = finalString;

                    await InsertOrMergeEntityAsync(table, meetingDetail); //inserts attendees' emails in table

                    return(await stepContext.PromptAsync(nameof(NumberPrompt <double>), new PromptOptions { Prompt = MessageFactory.Text("What will be duration of the meeting? (in hours)"), RetryPrompt = MessageFactory.Text("Invalid value, please enter a proper value") }, cancellationToken));
                }
            }
            await stepContext.Context.SendActivityAsync("Something went wrong. Please type anything to get started again.");

            return(await stepContext.EndDialogAsync(cancellationToken : cancellationToken));
        }
        // Gets recent mail the user has received within the last hour and displays up
        // to 5 of the emails in the bot.
        public static async Task ListRecentMailAsync(ITurnContext turnContext, TokenResponse tokenResponse)
        {
            if (turnContext == null)
            {
                throw new ArgumentNullException(nameof(turnContext));
            }

            if (tokenResponse == null)
            {
                throw new ArgumentNullException(nameof(tokenResponse));
            }

            var client   = new SimpleGraphClient(tokenResponse.Token);
            var messages = await client.GetRecentMailAsync();

            IMessageActivity reply = null;

            if (messages.Any())
            {
                var count = messages.Length;
                if (count > 5)
                {
                    count = 5;
                }

                reply = MessageFactory.Attachment(new List <Attachment>());
                reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;

                for (var i = 0; i < count; i++)
                {
                    var mail = messages[i];
                    var card = new HeroCard(
                        mail.Subject,
                        $"{mail.From.EmailAddress.Name} <{mail.From.EmailAddress.Address}>",
                        mail.BodyPreview,
                        new List <CardImage>()
                    {
                        new CardImage(
                            "https://botframeworksamples.blob.core.windows.net/samples/OutlookLogo.jpg",
                            "Outlook Logo"),
                    });
                    reply.Attachments.Add(card.ToAttachment());
                }
            }
            else
            {
                reply = MessageFactory.Text("Unable to find any recent unread mail.");
            }

            await turnContext.SendActivityAsync(reply);
        }
Beispiel #8
0
        private async Task <DialogTurnResult> CreateNewSecret(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var tokenResponse = (TokenResponse)stepContext.Result;

            if (tokenResponse != null)
            {
                var client = new SimpleGraphClient(tokenResponse.Token);
                var app    = await client.CreateNewPassword("10437c16-0e73-4971-9bba-9f5686009160");

                await stepContext.Context.SendActivityAsync($"Your app id is: {app.SecretText}");
            }

            return(await stepContext.EndDialogAsync(cancellationToken : cancellationToken));
        }
        protected async override Task <MessagingExtensionResponse> OnTeamsAppBasedLinkQueryAsync(ITurnContext <IInvokeActivity> turnContext, AppBasedLinkQuery query, CancellationToken cancellationToken)
        {
            var tokenResponse = await GetTokenResponse(turnContext, query.State, cancellationToken);

            if (tokenResponse == null || string.IsNullOrEmpty(tokenResponse.Token))
            {
                // There is no token, so the user has not signed in yet.
                // Retrieve the OAuth Sign in Link to use in the MessagingExtensionResult Suggested Actions
                var signInLink = await(turnContext.Adapter as IUserTokenProvider).GetOauthSignInLinkAsync(turnContext, _connectionName, cancellationToken);
                return(new MessagingExtensionResponse
                {
                    ComposeExtension = new MessagingExtensionResult
                    {
                        Type = "auth",
                        SuggestedActions = new MessagingExtensionSuggestedAction
                        {
                            Actions = new List <CardAction>
                            {
                                new CardAction
                                {
                                    Type = ActionTypes.OpenUrl,
                                    Value = signInLink,
                                    Title = "Bot Service OAuth",
                                },
                            },
                        },
                    },
                });
            }

            var client  = new SimpleGraphClient(tokenResponse.Token);
            var profile = await client.GetMyProfile();

            var imagelink = await client.GetPhotoAsync();

            var heroCard = new ThumbnailCard
            {
                Title  = "Thumbnail Card",
                Text   = $"Hello {profile.DisplayName}",
                Images = new List <CardImage> {
                    new CardImage(imagelink)
                }
            };
            var attachments = new MessagingExtensionAttachment(HeroCard.ContentType, null, heroCard);
            var result      = new MessagingExtensionResult("list", "result", new[] { attachments });

            return(new MessagingExtensionResponse(result));
        }
Beispiel #10
0
        private static async Task <User> GetUserAsync(ITurnContext turnContext, TokenResponse tokenResponse)
        {
            if (turnContext == null)
            {
                throw new ArgumentNullException(nameof(turnContext));
            }

            if (tokenResponse == null)
            {
                throw new ArgumentNullException(nameof(tokenResponse));
            }

            // Pull in the data from the Microsoft Graph.
            var client = new SimpleGraphClient(tokenResponse.Token);

            return(await client.GetMeAsync());
        }
        // Displays information about the user in the bot.
        public static async Task ListMeAsync(ITurnContext turnContext, TokenResponse tokenResponse)
        {
            if (turnContext == null)
            {
                throw new ArgumentNullException(nameof(turnContext));
            }

            if (tokenResponse == null)
            {
                throw new ArgumentNullException(nameof(tokenResponse));
            }

            // Pull in the data from the Microsoft Graph.
            var client = new SimpleGraphClient(tokenResponse.Token);
            var me     = await client.GetMeAsync();

            await turnContext.SendActivityAsync($"You are {me.DisplayName}.");
        }
Beispiel #12
0
        private async Task <DialogTurnResult> ShowMeetingTimeSuggestions(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            double duration      = Convert.ToDouble(stepContext.Context.TurnState["data"]);
            var    tokenResponse = (TokenResponse)stepContext.Result;

            if (tokenResponse?.Token != null)
            {
                // Pull in the data from the Microsoft Graph.
                var           client        = new SimpleGraphClient(tokenResponse.Token);
                MeetingDetail meetingDetail = await RetrieveMeetingDetailsAsync(table, userEmail, stepContext.Context.Activity.Conversation.Id); //retrives data from table

                timeSuggestions = await client.FindMeetingTimes(meetingDetail.Attendees, duration);                                              //returns meeting times

                if (timeSuggestions.Count == 0)
                {
                    await stepContext.Context.SendActivityAsync("No appropriate meeting slot found. Please try again by typing 'hi' and change date this time");

                    return(await stepContext.EndDialogAsync(cancellationToken : cancellationToken));
                }
                var cardOptions = new List <Choice>();
                for (int i = 0; i < timeSuggestions.Count; i++)
                {
                    cardOptions.Add(new Choice()
                    {
                        Value = timeSuggestions[i].Start.DateTime + " - " + timeSuggestions[i].End.DateTime
                    });                                                                                                                    //creates list of meeting time choices
                }



                return(await stepContext.PromptAsync(nameof(ChoicePrompt), new PromptOptions
                {
                    Prompt = MessageFactory.Text("These are the time suggestions. Click on the time slot for when you want the meeting to be set."),
                    RetryPrompt = MessageFactory.Text("Sorry, Please the valid choice"),
                    Choices = cardOptions,
                    Style = ListStyle.HeroCard, //displays choices as buttons
                }, cancellationToken));
            }
            await stepContext.Context.SendActivityAsync("Something went wrong. Please type anything to get started again.");

            return(await stepContext.EndDialogAsync(cancellationToken : cancellationToken));
        }
Beispiel #13
0
        private async Task <DialogTurnResult> SendMeetingInvite(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            string description   = (string)stepContext.Context.TurnState["data"];
            var    tokenResponse = (TokenResponse)stepContext.Result;

            if (tokenResponse?.Token != null)
            {
                var           client        = new SimpleGraphClient(tokenResponse.Token);
                MeetingDetail meetingDetail = await RetrieveMeetingDetailsAsync(table, userEmail, stepContext.Context.Activity.Conversation.Id);                            //retrieves current meeting details

                await client.SendMeetingInviteAsync(timeSuggestions[Int32.Parse(meetingDetail.TimeSlotChoice)], meetingDetail.Attendees, meetingDetail.Title, description); //creates event

                await stepContext.Context.SendActivityAsync("Meeting has been scheduled. Thank you!");
            }
            else
            {
                await stepContext.Context.SendActivityAsync("Something went wrong. Please type anything to get started again.");
            }
            return(await stepContext.EndDialogAsync(cancellationToken : cancellationToken));
        }
Beispiel #14
0
        private async Task <DialogTurnResult> LoginStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var tokenResponse = (TokenResponse)stepContext.Result;

            if (tokenResponse?.Token != null)
            {
                var client = new SimpleGraphClient(tokenResponse.Token);
                var me     = await client.GetMeAsync();

                var title = !string.IsNullOrEmpty(me.JobTitle) ?
                            me.JobTitle : "Unknown";

                await stepContext.Context.SendActivityAsync($"You're logged in as {me.DisplayName} ({me.UserPrincipalName}); you job title is: {title}");

                return(await stepContext.PromptAsync(nameof(ConfirmPrompt), new PromptOptions { Prompt = MessageFactory.Text("Would you like to view your token?") }, cancellationToken));
            }

            await stepContext.Context.SendActivityAsync(MessageFactory.Text("Login was not successful please try again."), cancellationToken);

            return(await stepContext.EndDialogAsync(cancellationToken : cancellationToken));
        }
        public static async Task RemoveUserAsync(ITurnContext turnContext, TokenResponse tokenResponse, string upn)
        {
            if (turnContext == null)
            {
                throw new ArgumentNullException(nameof(turnContext));
            }

            if (tokenResponse == null)
            {
                throw new ArgumentNullException(nameof(tokenResponse));
            }

            var client = new SimpleGraphClient(tokenResponse.Token);

            //need to check if the function executed correctly if it were to be implemented
            //await client.RemoveUserAsync(upn);

            await turnContext.SendActivityAsync($"The user: {upn} has been REMOVED.");

            await turnContext.SendActivityAsync(MessageFactory.Text("This is a DEMO, no write actions were executed"));
        }
Beispiel #16
0
        private async Task <DialogTurnResult> LoginStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var authenticatedUserIsAuthenticated = await _AuthenticatedUserAccessor.GetAsync(stepContext.Context, () => new AuthenticatedUser());

            if (authenticatedUserIsAuthenticated.IsAuthenticated)
            {
                return(await stepContext.ContinueDialogAsync());
            }

            // Get the token from the previous step. Note that we could also have gotten the
            // token directly from the prompt itself. There is an example of this in the next method.
            var tokenResponse = (TokenResponse)stepContext.Result;

            if (tokenResponse?.Token != null)
            {
                AuthenticatedUser AuthenticatedUser = new AuthenticatedUser();
                AuthenticatedUser.IsAuthenticated  = true;
                AuthenticatedUser.JwtSecurityToken = tokenResponse.Token;

                await _AuthenticatedUserAccessor.SetAsync(stepContext.Context, AuthenticatedUser);

                // Pull in the data from the Microsoft Graph.
                var client = new SimpleGraphClient(tokenResponse.Token);
                var me     = await client.GetMeAsync();

                var title = !string.IsNullOrEmpty(me.JobTitle) ?
                            me.JobTitle : "Unknown";

                await stepContext.Context.SendActivityAsync($"You're logged in as {me.DisplayName} ({me.UserPrincipalName}); you job title is: {title}");

                await stepContext.Context.SendActivityAsync("Your intent please:");

                //return await stepContext.PromptAsync(nameof(ConfirmPrompt), new PromptOptions { Prompt = MessageFactory.Text("Your intent please:") }, cancellationToken);
            }

            //await stepContext.Context.SendActivityAsync(MessageFactory.Text("Login was not successful please try again."), cancellationToken);

            return(await stepContext.EndDialogAsync(cancellationToken : cancellationToken));
        }
Beispiel #17
0
        private async Task <DialogTurnResult> AskForAttendees(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var tokenResponse = (TokenResponse)stepContext.Result; // Get the token from the previous step.

            if (tokenResponse?.Token != null)
            {
                // Pull in the data from the Microsoft Graph.
                var client = new SimpleGraphClient(tokenResponse.Token);
                var me     = await client.GetMeAsync();

                userEmail = me.UserPrincipalName;
                table     = CreateTableAsync("botdata");              //creates table if does not exist already
                MeetingDetail meetingDetail = new MeetingDetail(stepContext.Context.Activity.Conversation.Id, userEmail);
                await InsertOrMergeEntityAsync(table, meetingDetail); //inserts user's email in table

                return(await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions { Prompt = MessageFactory.Text("With whom would you like to set up a meeting?") }, cancellationToken));
            }

            await stepContext.Context.SendActivityAsync("Something went wrong. Please type anything to get started again.");

            return(await stepContext.EndDialogAsync(cancellationToken : cancellationToken));
        }
        // Enable the user to send an email via the bot.
        public static async Task SendMailAsync(ITurnContext turnContext, TokenResponse tokenResponse, string recipient)
        {
            if (turnContext == null)
            {
                throw new ArgumentNullException(nameof(turnContext));
            }

            if (tokenResponse == null)
            {
                throw new ArgumentNullException(nameof(tokenResponse));
            }

            var client = new SimpleGraphClient(tokenResponse.Token);
            var me     = await client.GetMeAsync();

            await client.SendMailAsync(
                recipient,
                "Message from a bot!",
                $"Hi there! I had this message sent from a bot. - Your friend, {me.DisplayName}");

            await turnContext.SendActivityAsync(
                $"I sent a message to '{recipient}' from your account.");
        }
Beispiel #19
0
        // Displays information about the user in the bot.
        public static async Task ListMeAsync(ITurnContext turnContext, TokenResponse tokenResponse)
        {
            if (turnContext == null)
            {
                throw new ArgumentNullException(nameof(turnContext));
            }

            if (tokenResponse == null)
            {
                throw new ArgumentNullException(nameof(tokenResponse));
            }

            // Pull in the data from the Microsoft Graph.
            var client = new SimpleGraphClient(tokenResponse.Token);
            var me     = await client.GetMeAsync();

            var manager = await client.GetManagerAsync();

            var photoResponse = await client.GetPhotoAsync();

            // Generate the reply activity.
            var reply     = turnContext.Activity.CreateReply();
            var photoText = string.Empty;

            if (photoResponse != null)
            {
                var replyAttachment = new Attachment(photoResponse.ContentType, photoResponse.Base64String);
                reply.Attachments.Add(replyAttachment);
            }
            else
            {
                photoText = "Consider adding an image to your Outlook profile.";
            }

            reply.Text = $"You are {me.DisplayName} and you report to {manager.DisplayName}. {photoText}";
            await turnContext.SendActivityAsync(reply);
        }
        public static async Task CreateUserAsync(ITurnContext turnContext, TokenResponse tokenResponse, UserProfile userProfile)
        {
            if (turnContext == null)
            {
                throw new ArgumentNullException(nameof(turnContext));
            }

            if (tokenResponse == null)
            {
                throw new ArgumentNullException(nameof(tokenResponse));
            }

            var client = new SimpleGraphClient(tokenResponse.Token);

            User cUser = new User {
                AccountEnabled    = true,
                DisplayName       = userProfile.GivenName + " " + userProfile.SurName,
                UserPrincipalName = userProfile.UserPrincipalName,
                GivenName         = userProfile.GivenName,
                Surname           = userProfile.SurName,
                Department        = userProfile.Department,
                JobTitle          = userProfile.JobTitle,
                PasswordProfile   = new PasswordProfile
                {
                    ForceChangePasswordNextSignIn = true,
                    Password = userProfile.Password
                }
            };

            //need to check if the function executed correctly if it were to be implemented
            //await client.CreateUserAsync(cUser);

            await turnContext.SendActivityAsync(MessageFactory.Text($"{JsonConvert.SerializeObject(cUser, Formatting.Indented)}"));

            await turnContext.SendActivityAsync(MessageFactory.Text("This is a DEMO, no write actions were executed"));
        }
        public static async Task CheckLicensesAsync(ITurnContext turnContext, TokenResponse tokenResponse)
        {
            if (turnContext == null)
            {
                throw new ArgumentNullException(nameof(turnContext));
            }

            if (tokenResponse == null)
            {
                throw new ArgumentNullException(nameof(tokenResponse));
            }

            var client             = new SimpleGraphClient(tokenResponse.Token);
            IMessageActivity reply = null;

            //NO RIGHTS AVAILABLE IN DEMO
            //var licenses = await client.GetLicensesAsync();

            //if (licenses.Any())
            //{
            //    var count = licenses.Length;
            //    reply = MessageFactory.Attachment(new List<Attachment>());
            //    reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;

            //    for (var i = 0; i < count; i++)
            //    {
            //        var license = licenses[i];
            //        var card = new HeroCard(
            //            license.SkuPartNumber,
            //            license.SkuId.ToString(),
            //            "INFO ABOUT LICENSE (api can't include expiry date)",
            //            new List<CardImage>()
            //            {
            //                new CardImage(
            //                    "https://us.123rf.com/450wm/aquir/aquir2003/aquir200308059/143107865-subscription-stamp-subscription-vintage-gray-label-sign.jpg?ver=6",
            //                    "Outlook Logo"),
            //            });
            //        reply.Attachments.Add(card.ToAttachment());
            //    }
            //}
            //else
            //{
            //    reply = MessageFactory.Text("Unable to find any recent unread mail.");
            //}


            //COMMENT THIS SECTION WHEN IMPLEMENTION ABOVE IS UNCOMMENTEDD
            reply = MessageFactory.Attachment(new List <Attachment>());
            reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;

            for (var i = 0; i < 5; i++)
            {
                //would replace with properties out of var licenses
                var card = new HeroCard(
                    "Enterprise E5 (with Audio Conferencing)", "ENTERPRISEPREMIUM",
                    "INFO ABOUT LICENSE (api can't include expiry date)",
                    new List <CardImage>()
                {
                    new CardImage(
                        "https://www.infserv.com/images/Artikels/office2.jpg",
                        "Office365 Logo"),
                });
                reply.Attachments.Add(card.ToAttachment());
            }
            //COMMENT THIS SECTION WHEN IMPLEMENTION ABOVE IS UNCOMMENTEDD

            await turnContext.SendActivityAsync(reply);

            await turnContext.SendActivityAsync(MessageFactory.Text("This is a DEMO, these cards are made from fictional data"));
        }
        protected override async Task <MessagingExtensionActionResponse> OnTeamsMessagingExtensionFetchTaskAsync(ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction action, CancellationToken cancellationToken)
        {
            if (action.CommandId.ToUpper() == "SHOWPROFILE")
            {
                var state         = action.State; // Check the state value
                var tokenResponse = await GetTokenResponse(turnContext, state, cancellationToken);

                if (tokenResponse == null || string.IsNullOrEmpty(tokenResponse.Token))
                {
                    // There is no token, so the user has not signed in yet.

                    // Retrieve the OAuth Sign in Link to use in the MessagingExtensionResult Suggested Actions
                    var signInLink = await(turnContext.Adapter as IUserTokenProvider).GetOauthSignInLinkAsync(turnContext, _connectionName, cancellationToken);

                    return(new MessagingExtensionActionResponse
                    {
                        ComposeExtension = new MessagingExtensionResult
                        {
                            Type = "auth",
                            SuggestedActions = new MessagingExtensionSuggestedAction
                            {
                                Actions = new List <CardAction>
                                {
                                    new CardAction
                                    {
                                        Type = ActionTypes.OpenUrl,
                                        Value = signInLink,
                                        Title = "Bot Service OAuth",
                                    },
                                },
                            },
                        },
                    });
                }
                var client  = new SimpleGraphClient(tokenResponse.Token);
                var profile = await client.GetMyProfile();

                var imagelink = _siteUrl + await client.GetPublicURLForProfilePhoto(profile.Id);

                return(new MessagingExtensionActionResponse
                {
                    Task = new TaskModuleContinueResponse
                    {
                        Value = new TaskModuleTaskInfo
                        {
                            Card = GetProfileCard(profile, imagelink),
                            Height = 250,
                            Width = 400,
                            Title = "Adaptive Card: Inputs",
                        },
                    },
                });
            }
            if (action.CommandId.ToUpper() == "SIGNOUTCOMMAND")
            {
                await(turnContext.Adapter as IUserTokenProvider).SignOutUserAsync(turnContext, _connectionName, turnContext.Activity.From.Id, cancellationToken);

                return(new MessagingExtensionActionResponse
                {
                    Task = new TaskModuleContinueResponse
                    {
                        Value = new TaskModuleTaskInfo
                        {
                            Card = new Microsoft.Bot.Schema.Attachment
                            {
                                Content = new AdaptiveCard(new AdaptiveSchemaVersion("1.0"))
                                {
                                    Body = new List <AdaptiveElement>()
                                    {
                                        new AdaptiveTextBlock()
                                        {
                                            Text = "You have been signed out."
                                        }
                                    },
                                    Actions = new List <AdaptiveAction>()
                                    {
                                        new AdaptiveSubmitAction()
                                        {
                                            Title = "Close"
                                        }
                                    },
                                },
                                ContentType = AdaptiveCard.ContentType,
                            },
                            Height = 200,
                            Width = 400,
                            Title = "Adaptive Card: Inputs",
                        },
                    },
                });
            }
            return(null);
        }
        protected override async Task <MessagingExtensionResponse> OnTeamsMessagingExtensionQueryAsync(ITurnContext <IInvokeActivity> turnContext, MessagingExtensionQuery action, CancellationToken cancellationToken)
        {
            var tokenResponse = await GetTokenResponse(turnContext, action.State, cancellationToken);

            if (tokenResponse == null || string.IsNullOrEmpty(tokenResponse.Token))
            {
                // There is no token, so the user has not signed in yet.
                // Retrieve the OAuth Sign in Link to use in the MessagingExtensionResult Suggested Actions
                var signInLink = await(turnContext.Adapter as IUserTokenProvider).GetOauthSignInLinkAsync(turnContext, _connectionName, cancellationToken);
                return(new MessagingExtensionResponse
                {
                    ComposeExtension = new MessagingExtensionResult
                    {
                        Type = "auth",
                        SuggestedActions = new MessagingExtensionSuggestedAction
                        {
                            Actions = new List <CardAction>
                            {
                                new CardAction
                                {
                                    Type = ActionTypes.OpenUrl,
                                    Value = signInLink,
                                    Title = "Bot Service OAuth",
                                },
                            },
                        },
                    },
                });
            }
            var client = new SimpleGraphClient(tokenResponse.Token);
            var me     = await client.GetMyProfile();

            var imagelink = await client.GetPhotoAsync();

            var previewcard = new ThumbnailCard
            {
                Title  = me.DisplayName,
                Images = new List <CardImage> {
                    new CardImage {
                        Url = imagelink
                    }
                }
            };
            var attachment = new MessagingExtensionAttachment
            {
                ContentType = ThumbnailCard.ContentType,
                Content     = previewcard,
                Preview     = previewcard.ToAttachment()
            };

            return(new MessagingExtensionResponse
            {
                ComposeExtension = new MessagingExtensionResult
                {
                    Type = "result",
                    AttachmentLayout = "list",
                    Attachments = new List <MessagingExtensionAttachment> {
                        attachment
                    }
                }
            });
        }
Beispiel #24
0
        private async Task <DialogTurnResult> ProcessStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            if (stepContext.Result != null)
            {
                // We do not need to store the token in the bot. When we need the token we can
                // send another prompt. If the token is valid the user will not need to log back in.
                // The token will be available in the Result property of the task.
                var tokenResponse = stepContext.Result as TokenResponse;

                // If we have the token use the user is authenticated so we may use it to make API calls.
                if (tokenResponse?.Token != null)
                {
                    var command = ((string)stepContext.Values["command"] ?? string.Empty).ToLowerInvariant();
                    var events  = await SimpleGraphClient.GetAuthenticatedClient(tokenResponse.Token).GetCalendarEvents();

                    var groupevents = await SimpleGraphClient.GetAuthenticatedClient(tokenResponse.Token).GetGroupCalendarEvents();

                    if (command == "mycalendar")
                    {
                        string eventsFormatted = string.Join("\n",
                                                             events.Select(s => $"- {s.Subject} from {DateTime.Parse(s.Start.DateTime).ToShortTimeString()} till {DateTime.Parse(s.End.DateTime).ToShortTimeString()}")
                                                             .ToList());

                        await stepContext.Context.SendActivityAsync("You have the following events: \n" + eventsFormatted,
                                                                    cancellationToken : cancellationToken);
                    }
                    else if (command.StartsWith("groupcalendar"))
                    {
                        string groupeventsFormatted = string.Join("\n",
                                                                  groupevents.Select(s => $"- {s.Subject} from {DateTime.Parse(s.Start.DateTime).ToShortTimeString()} till {DateTime.Parse(s.End.DateTime).ToShortTimeString()}")
                                                                  .ToList());

                        await stepContext.Context.SendActivityAsync("Your group have the following events: \n" + groupeventsFormatted,
                                                                    cancellationToken : cancellationToken);
                    }

                    else if (command.StartsWith("setappointment"))
                    {
                        return(await stepContext.BeginDialogAsync(nameof(AppointmentInfoDialog), tokenResponse, cancellationToken));
                    }
                    else if (command.StartsWith("create group calendar"))
                    {
                        await SimpleGraphClient.GetAuthenticatedClient(tokenResponse.Token).CreateGroupCalendar();

                        await stepContext.Context.SendActivityAsync("DEMO-GROUP-CALENDAR created \n",
                                                                    cancellationToken : cancellationToken);
                    }
                    else
                    {
                        // await stepContext.Context.SendActivityAsync(MessageFactory.Text($"Your token is: {tokenResponse.Token}"), cancellationToken);
                        await stepContext.Context.SendActivityAsync(MessageFactory.Text($"Oops! Thats not a valid entry"), cancellationToken);
                    }
                }
            }
            else
            {
                await stepContext.Context.SendActivityAsync(MessageFactory.Text("We couldn't log you in. Please try again later."), cancellationToken);
            }

            return(await stepContext.EndDialogAsync(cancellationToken : cancellationToken));
        }