private async Task <DialogTurnResult> MetricPhase2Async(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var createIdeaOptions = (CreateIdeaOptions)stepContext.Options;

            if (createIdeaOptions.Metric != null)
            {
                return(await stepContext.NextAsync(createIdeaOptions.Metric, cancellationToken));
            }

            var tokenResponse = (TokenResponse)stepContext.Result;

            if (tokenResponse?.Token == null)
            {
                await stepContext.Context.SendActivityAsync(MessageFactory.Text("Login was not successful please try again."), cancellationToken);

                return(await stepContext.ReplaceDialogAsync(nameof(WaterfallDialog), createIdeaOptions, cancellationToken));
            }

            var userProfile = await UserProfileAccessor.GetAsync(stepContext.Context);

            var service = new MetricsService(tokenResponse.Token, Configuration["BaseSPSiteUrl"]);
            var metrics = (await service.GetActiveMetricsAsync(userProfile.SelectedTeam.Id)).ToList();

            metrics.Add(new Metric {
                Id = 0, Name = "Other"
            });
            var promptOptions = new PromptOptions
            {
                Prompt  = MessageFactory.Text("What metric does this idea try to move?"),
                Choices = metrics.Select(i => new Choice(i.Name)).ToArray()
            };

            return(await stepContext.PromptAsync(nameof(ChoicePrompt), promptOptions, cancellationToken));
        }
Example #2
0
        /**
         * Waterfall step to prompt for user's name
         *
         * @param {DialogContext} Dialog context
         * @param {WaterfallStepContext} water fall step context
         */
        private async Task<DialogTurnResult> AskForUserNameAsync(
                                                WaterfallStepContext stepContext,
                                                CancellationToken cancellationToken)
        {
            var context = stepContext.Context;

            // Get user profile.
            var userProfile = await UserProfileAccessor.GetAsync(context, () => new UserProfile(null, null));

            // Get on turn properties.
            var onTurnProperty = await OnTurnAccessor.GetAsync(context, () => new OnTurnProperty("None", new List<EntityProperty>()));

            // Handle case where user is re-introducing themselves.
            // This flow is triggered when we are not in the middle of who-are-you dialog
            // and the user says something like 'call me {username}' or 'my name is {username}'.

            // Get user name entities from on turn property (from the cafe bot dispatcher LUIS model)
            var userNameInOnTurnProperty = (onTurnProperty.Entities ?? new List<EntityProperty>()).Where(item => ((item.EntityName == userNameEntity) || (item.EntityName == userNamePatternAnyEntity)));
            if (userNameInOnTurnProperty.Count() > 0)
            {
                // Get user name from on turn property
                var userName = userNameInOnTurnProperty.First().Value as string;

                // Capitalize user name
                userName = char.ToUpper(userName[0]) + userName.Substring(1);

                // Set user name
                await UserProfileAccessor.SetAsync(context, new UserProfile(userName));

                // End this step so we can greet the user.
                return await stepContext.NextAsync(haveUserName);
            }

            // Prompt user for name if
            // we have an invalid or empty user name or
            // if the user name was previously set to 'Human'
            if (userProfile == null || string.IsNullOrWhiteSpace(userProfile.UserName) || userProfile.UserName.Equals("Human", StringComparison.Ordinal))
            {
                await context.SendActivityAsync("Hello, I'm the Contoso Cafe Bot.");

                // Begin the prompt to ask user their name
                var opts = new PromptOptions
                {
                    Prompt = new Activity
                    {
                        Type = ActivityTypes.Message,
                        Text = "What's your name?",
                    },
                };
                return await stepContext.PromptAsync(askUserNamePrompt, opts);
            }
            else
            {
                // Already have the user name. So just greet them.
                await context.SendActivityAsync($"Hello {userProfile.UserName}, Nice to meet you again! I'm the Contoso Cafe Bot.");

                // End this dialog. We are skipping the next water fall step deliberately.
                return await stepContext.EndDialogAsync();
            }
        }
Example #3
0
        private async Task <DialogTurnResult> AmountPeopleStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var state = await UserProfileAccessor.GetAsync(stepContext.Context);

            if (stepContext.Result != null)
            {
                var time = stepContext.Result as string;
                state.Time = time;
            }

            if (state.AmountPeople == null)
            {
                var msg  = "How many people will you need the reservation for?";
                var opts = new PromptOptions
                {
                    Prompt = new Activity
                    {
                        Type = ActivityTypes.Message,
                        Text = msg,
                        // Add the message to speak
                    },
                };
                return(await stepContext.PromptAsync(AmountPeoplePrompt, opts));
            }
            else
            {
                return(await stepContext.NextAsync());
            }
        }
        private async Task <DialogTurnResult> OwnerPhase2Async(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var createIdeaOptions = (CreateIdeaOptions)stepContext.Options;

            if (createIdeaOptions.Owner != null)
            {
                return(await stepContext.NextAsync(createIdeaOptions.Owner, cancellationToken));
            }

            var tokenResponse = (TokenResponse)stepContext.Result;

            if (tokenResponse?.Token == null)
            {
                await stepContext.Context.SendActivityAsync(MessageFactory.Text("Login was not successful please try again."), cancellationToken);

                return(await stepContext.ReplaceDialogAsync(nameof(WaterfallDialog), createIdeaOptions, cancellationToken));
            }

            var userProfile = await UserProfileAccessor.GetAsync(stepContext.Context);

            var service = new TeamsService(tokenResponse.Token);
            var members = await service.GetTeamMembersAsync(userProfile.SelectedTeam.Id);

            stepContext.Values["members"] = members;

            var promptOptions = new PromptOptions
            {
                Prompt  = MessageFactory.Text("Thanks. Please identify the idea owner."),
                Choices = members.Select(i => new Choice(i.DisplayName)).ToArray(),
                Style   = ListStyle.HeroCard
            };

            return(await stepContext.PromptAsync(nameof(ChoicePrompt), promptOptions, cancellationToken));
        }
Example #5
0
        public async Task SetUserProfileAsync(UserProfile profile, DialogContext dialogContext
                                              , CancellationToken cancellationToken = default)
        {
            //Also update the dialog contexts state
            await UserProfileAccessor.SetAsync(dialogContext.Context, profile, cancellationToken);

            dialogContext.GetState().SetValue("user.UserProfile", profile);
        }
Example #6
0
        /// <summary>
        /// Gets the user role profile by user name and password.
        /// </summary>
        /// <param name="UserName">Name of the user.</param>
        /// <param name="Password">The password.</param>
        /// <returns>UserProfile.</returns>
        public UserProfile GetUserRoleProfileByUserNameAndPassword(string UserName, string Password)
        {
            // create a list to hold the returned data
            var userProfileDetail = new UserProfile();

            userProfileDetail = UserProfileAccessor.FetchUserProfileDetail(UserName, Password);


            return(userProfileDetail);
        }
Example #7
0
        public UserProfile GetUserProfileByUserID(int userId)
        {
            // create a list to hold the returned data
            var userProfileDetail = new UserProfile();

            userProfileDetail = UserProfileAccessor.GetUserProfileByUserID(userId);


            return(userProfileDetail);
        }
        private async Task <DialogTurnResult> SelectTeamStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var userProfile = await UserProfileAccessor.GetAsync(stepContext.Context);

            if (userProfile.SelectedTeam == null)
            {
                return(await stepContext.BeginDialogAsync(nameof(SelectTeamDialog), cancellationToken : cancellationToken));
            }
            return(await stepContext.NextAsync(userProfile.SelectedTeam, cancellationToken));
        }
        protected async Task <DialogTurnResult> SignStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var userProfile = await UserProfileAccessor.GetAsync(stepContext.Context);

            if (userProfile.SelectedTeam != null)
            {
                var activity = MessageFactory.Text($"Your current team is **{userProfile.SelectedTeam.DisplayName}**");
                activity.TextFormat = "markdown";
                await stepContext.Context.SendActivityAsync(activity);
            }
            return(await stepContext.BeginDialogAsync(nameof(OAuthPrompt), null, cancellationToken));
        }
Example #10
0
        /**
          * Waterfall step to finalize user's response and greet user.
          *
          * @param {DialogContext} Dialog context
          * @param {WaterfallStepContext} water fall step context
          */
        private async Task<DialogTurnResult> GreetUserAsync(
                                                WaterfallStepContext stepContext,
                                                CancellationToken cancellationToken)
        {
            var context = stepContext.Context;
            if (stepContext.Result != null)
            {
                var userProfile = await UserProfileAccessor.GetAsync(context);
                await context.SendActivityAsync($"Hey there {userProfile.UserName}!, nice to meet you!");
            }

            return await stepContext.EndDialogAsync();
        }
        /// <summary>
        /// Validates the new user.
        /// </summary>
        /// <param name="username">The username.</param>
        /// <param name="newPassword">The new password.</param>
        /// <returns>AccessToken.</returns>
        /// <exception cref="System.ApplicationException">Data not found.</exception>
        public static AccessToken ValidateNewUser(string username, string newPassword)
        {
            // check for new user
            if (1 == UserProfileAccessor.FindUserByUsernameAndPassword(username, "NEWUSER"))
            {
                UserProfileAccessor.SetPasswordForUsername(username, "NEWUSER", newPassword.HashSha256());
            }
            else
            {
                throw new ApplicationException("Data not found.");
            }

            return(ValidateExistingUser(username, newPassword));
        }
Example #12
0
        /// <summary>
        /// Determines whether [is valid user] [the specified user name].
        /// </summary>
        /// <param name="UserName">Name of the user.</param>
        /// <param name="Password">The password.</param>
        /// <returns><c>true</c> if [is valid user] [the specified user name]; otherwise, <c>false</c>.</returns>
        public static bool IsValidUser(string UserName, string Password)
        {
            var userProfileDetail = new UserProfile();

            userProfileDetail = UserProfileAccessor.FetchUserProfileDetail(UserName, Password);

            if (userProfileDetail != null)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Example #13
0
 public bool UpdateUser(UserProfile profile)
 {
     try
     {
         if (UserProfileAccessor.InsertUpdateUser(profile, false) >= 1)
         {
             return(true);
         }
         else
         {
             return(false);
         }
     }
     catch (Exception)
     {
         throw;
     }
 }
        private async Task <DialogTurnResult> FinalStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var teamName = ((FoundChoice)stepContext.Result).Value;

            var teams = (Models.Team[])stepContext.Values["teams"];
            var team  = teams.FirstOrDefault(i => i.DisplayName == teamName);

            var userProfile = await UserProfileAccessor.GetAsync(stepContext.Context);

            userProfile.SelectedTeam = team;

            var activity = MessageFactory.Text($"You selected **{team.DisplayName}**.");

            activity.TextFormat = "markdown";
            await stepContext.Context.SendActivityAsync(activity);

            return(await stepContext.EndDialogAsync(team, cancellationToken));
        }
        private async Task <DialogTurnResult> ShowTeamsStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var tokenResponse = (TokenResponse)stepContext.Result;

            if (tokenResponse?.Token == null)
            {
                await stepContext.Context.SendActivityAsync(MessageFactory.Text("Login was not successful please try again."), cancellationToken);

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

            var service = new TeamsService(tokenResponse.Token);
            var teams   = await service.GetJoinedTeamsAsync();

            if (teams.Length == 0)
            {
                await stepContext.Context.SendActivityAsync("Sorry, you do not belong to any team at the moment.");

                return(await stepContext.EndDialogAsync(null, cancellationToken));
            }
            else if (teams.Length == 1)
            {
                var team = teams.First();

                var userProfile = await UserProfileAccessor.GetAsync(stepContext.Context);

                userProfile.SelectedTeam = team;

                await stepContext.Context.SendActivityAsync($"You only have one team: {team.DisplayName}. It was selected automatically.");

                return(await stepContext.EndDialogAsync(team, cancellationToken));
            }
            else
            {
                stepContext.Values["teams"] = teams;
                var promptOptions = new PromptOptions
                {
                    Prompt  = MessageFactory.Text("Please select one of you teams:"),
                    Choices = teams.Select(i => new Choice(i.DisplayName)).ToArray(),
                    Style   = ListStyle.HeroCard
                };
                return(await stepContext.PromptAsync(nameof(ChoicePrompt), promptOptions, cancellationToken));
            }
        }
Example #16
0
        private async Task <DialogTurnResult> InitializeStateStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var state = await UserProfileAccessor.GetAsync(stepContext.Context, () => null);

            if (state == null)
            {
                var reservationDataOpt = stepContext.Options as ReservationData;
                if (reservationDataOpt != null)
                {
                    await UserProfileAccessor.SetAsync(stepContext.Context, reservationDataOpt);
                }
                else
                {
                    await UserProfileAccessor.SetAsync(stepContext.Context, new ReservationData());
                }
            }

            return(await stepContext.NextAsync());
        }
Example #17
0
        /// <summary>
        /// Gets the user profile list.
        /// </summary>
        /// <returns>List&lt;UserProfile&gt;.</returns>
        /// <exception cref="System.ApplicationException">There were no records found.</exception>
        public List <UserProfile> GetUserProfileList()
        {
            try
            {
                var userProfileList = UserProfileAccessor.FetchUserProfileList();

                if (userProfileList.Count > 0)
                {
                    return(userProfileList);
                }
                else
                {
                    throw new ApplicationException("There were no records found.");
                }
            }
            catch (Exception)
            {
                // *** we should sort the possible exceptions and return friendly messages for each
                throw;
            }
        }
Example #18
0
        public bool InsertNewUser(string firstName, string lastName, string middleName, string userName, string emailID, string phone, string address, string postalcode, string city,
                                  string state, string roleName, bool isActive, string password)
        {
            try
            {
                try
                {
                    var userProfile = new UserProfile()
                    {
                        FirstName    = firstName,
                        LastName     = lastName,
                        MiddleName   = middleName,
                        UserName     = userName,
                        EmailAddress = emailID,
                        Phone        = phone,
                        IsActive     = isActive,
                        Address      = address,
                        Zip          = postalcode,
                        City         = city,
                        State        = state,
                        RoleName     = roleName,
                        Password     = password
                    };
                    if (UserProfileAccessor.InsertUpdateUser(userProfile, true) >= 1)
                    {
                        return(true);
                    }
                }
                catch (Exception)
                {
                    throw;
                }

                return(false);
            }
            catch (Exception)
            {
                throw new ApplicationException("No Records were inserted");
            }
        }
Example #19
0
        private async Task <DialogTurnResult> FinalStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var state = await UserProfileAccessor.GetAsync(stepContext.Context);

            if (stepContext.Result != null)
            {
                var    confirmation = (bool)stepContext.Result;
                string msg          = null;
                if (confirmation)
                {
                    msg = $"Great, we will be expecting you this {state.Time}. Thanks for your reservation {state.FirstName}!";
                }
                else
                {
                    msg = "Thanks for using the Contoso Assistance. See you soon!";
                }

                await stepContext.Context.SendActivityAsync(msg);
            }

            return(await stepContext.EndDialogAsync());
        }
Example #20
0
        private async Task <DialogTurnResult> TimeStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var state = await UserProfileAccessor.GetAsync(stepContext.Context);

            if (string.IsNullOrEmpty(state.Time))
            {
                var msg  = "When do you need the reservation?";
                var opts = new PromptOptions
                {
                    Prompt = new Activity
                    {
                        Type = ActivityTypes.Message,
                        Text = msg,
                        // Add the message to speak
                    },
                };
                return(await stepContext.PromptAsync(TimePrompt, opts));
            }
            else
            {
                return(await stepContext.NextAsync());
            }
        }
Example #21
0
        private async Task <DialogTurnResult> ConfirmationStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var state = await UserProfileAccessor.GetAsync(stepContext.Context);

            if (stepContext.Result != null)
            {
                state.FullName = stepContext.Result as string;
            }

            if (state.Confirmed == null)
            {
                var msg      = $"Ok. Let me confirm the information: This is a reservation for {state.Time} for {state.AmountPeople} people. Is that correct?";
                var retryMsg = "Please confirm, say 'yes' or 'no' or something like that.";

                var opts = new PromptOptions
                {
                    Prompt = new Activity
                    {
                        Type = ActivityTypes.Message,
                        Text = msg,
                        // Add the message to speak
                    },
                    RetryPrompt = new Activity
                    {
                        Type = ActivityTypes.Message,
                        Text = retryMsg,
                        // Add the retry message to speak
                    },
                };
                return(await stepContext.PromptAsync(ConfirmationPrompt, opts));
            }
            else
            {
                return(await stepContext.NextAsync());
            }
        }
Example #22
0
 public async Task <UserProfile> GetUserProfileAsync(ITurnContext turnContext
                                                     , CancellationToken cancellationToken = default)
 {
     return(await UserProfileAccessor.GetAsync(turnContext, () => new UserProfile(), cancellationToken));
 }
Example #23
0
 public bool DeleteUser(int userID)
 {
     return(UserProfileAccessor.DeleteUser(userID) > 0);
 }
        private async Task <DialogTurnResult> ListIdeasPhase2Async(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var tokenResponse = (TokenResponse)stepContext.Result;

            if (tokenResponse?.Token == null)
            {
                await stepContext.Context.SendActivityAsync(MessageFactory.Text("Login was not successful please try again."), cancellationToken);

                return(await stepContext.EndDialogAsync(null, cancellationToken));
            }

            var handler  = new JwtSecurityTokenHandler();
            var token    = handler.ReadJwtToken(tokenResponse.Token);
            var tenantId = token.Claims.FirstOrDefault(i => i.Type == "tid").Value;

            var userProfile = await UserProfileAccessor.GetAsync(stepContext.Context);

            var team = userProfile.SelectedTeam;

            var listIdeasOptions = (ListIdeasOptions)stepContext.Options;

            var plannerService = new PlannerService(tokenResponse.Token);
            var ideaService    = new IdeaService(tokenResponse.Token);

            var plan = await plannerService.GetTeamPlanAsync(team.Id, team.DisplayName);

            if (plan == null)
            {
                await stepContext.Context.SendActivityAsync(MessageFactory.Text("Could not found the plan."), cancellationToken);

                return(await stepContext.EndDialogAsync(null, cancellationToken));
            }

            var bucketName = ideaService.GetBucketName(listIdeasOptions.Status);
            var ideas      = await ideaService.GetAsync(plan.Id, bucketName, listIdeasOptions.From);

            var summary = ideas.Length > 0
                ? $"Getting {ideas.Length} {(ideas.Length > 1 ? "ideas" : "idea")} from Microsoft Planner, please wait..."
                : "No idea was found.";
            await stepContext.Context.SendActivityAsync(summary);

            foreach (var bucket in IdeasPlan.Buckets.All)
            {
                var bucketIdeas = ideas.Where(i => StringComparer.InvariantCultureIgnoreCase.Equals(i.Bucket, bucket)).ToArray();
                if (!bucketIdeas.Any())
                {
                    continue;
                }

                if (string.IsNullOrEmpty(bucketName))
                {
                    await stepContext.Context.SendActivityAsync($"{bucket} ({bucketIdeas.Length + " " + (bucket.Length > 1 ? "ideas" : "idea")})");
                }

                int pageSize  = 6;
                int pageCount = (bucketIdeas.Length + pageSize - 1) / pageSize;
                for (int page = 0; page < pageCount; page++)
                {
                    var attachments = new List <Attachment>();
                    var pageIdeas   = bucketIdeas.Skip(pageSize * page).Take(pageSize).ToArray();
                    foreach (var idea in pageIdeas)
                    {
                        await ideaService.GetDetailsAsync(idea);

                        var url    = ideaService.GetIdeaUrl(tenantId, team.Id, plan.Id, idea.Id);
                        var owners = $"Owners: {string.Join(",", idea.Owners)}";
                        var text   = $"Start Date<br/>{idea.StartDate?.DateTime.ToShortDateString()}";
                        if (!string.IsNullOrEmpty(idea.Description))
                        {
                            text += $"<br/><br/>{idea.Description.Replace("\r\n", "<br/>").Replace("\n", "<br/>")}";
                        }
                        var viewAction = new CardAction(ActionTypes.OpenUrl, "View", value: url);
                        var heroCard   = new HeroCard(idea.Title, owners, text, buttons: new List <CardAction> {
                            viewAction
                        });
                        attachments.Add(heroCard.ToAttachment());
                    }

                    var message = MessageFactory.Carousel(attachments);
                    await stepContext.Context.SendActivityAsync(message);
                }
            }
            return(await stepContext.EndDialogAsync(null, cancellationToken));
        }