Esempio n. 1
0
        private void SaveLog(Activity activity)
        {
            // *************************
            // Log to Database
            // *************************

            // Instantiate the BotData dbContext
            Models.BotDataEntities DB = new Models.BotDataEntities();
            // Create a new UserLog object
            Models.UserLog NewUserLog = new Models.UserLog();

            // Set the properties on the UserLog object
            NewUserLog.Channel  = activity.ChannelId;
            NewUserLog.UserID   = activity.From.Id;
            NewUserLog.UserName = activity.From.Name;
            NewUserLog.created  = DateTime.UtcNow;
            NewUserLog.Message  = activity.Text.Truncate(500);

            try
            {
                // Add the UserLog object to UserLogs
                DB.UserLogs.Add(NewUserLog);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            // Save the changes to the database
            DB.SaveChanges();
        }
Esempio n. 2
0
        private async Task PlayAgainAsync(IDialogContext context, IAwaitable <bool> result)
        {
            // Generate new random number
            Random random = new Random();

            this.intNumberToGuess = random.Next(1, 6);

            // Reset attempts
            this.intAttempts = 1;

            // Get the response from the user
            var confirm = await result;

            if (confirm) // They said yes
            {
                // Start a new Game
                // Create a response
                // This time call the ** ShowButtons ** method
                Activity replyToConversation =
                    ShowButtons(context,
                                "Hi Welcome! - Guess a number between 1 and 5 \n\n Type 'High Scores' to see high scores");

                // *************************
                // Log to Database
                // *************************

                // Instantiate the BotData dbContext
                Models.BotDataEntities DB = new Models.BotDataEntities();
                // Create a new UserLog object
                Models.UserLog NewUserLog = new Models.UserLog();

                // Set the properties on the UserLog object
                NewUserLog.Channel  = replyToConversation.ChannelId;
                NewUserLog.UserID   = replyToConversation.From.Id;
                NewUserLog.UserName = replyToConversation.From.Name;
                NewUserLog.created  = DateTime.UtcNow;
                // This logs the message being sent to the user
                NewUserLog.Message = replyToConversation.Text.Truncate(500);

                // Add the UserLog object to UserLogs
                DB.UserLogs.Add(NewUserLog);
                // Save the changes to the database
                DB.SaveChanges();

                await context.PostAsync(replyToConversation);

                context.Wait(MessageReceivedAsync);
            }
            else // They said no
            {
                await context.PostAsync("Goodbye!(heart)");

                context.Wait(MessageReceivedAsync);
            }
        }
Esempio n. 3
0
        private void ShowHighScores(Activity activity)
        {
            // This method will take an Activity and return a response
            // that will conatin the current High Scores

            // Connect to the database
            Models.BotDataEntities DB = new Models.BotDataEntities();

            // Get Yesterday
            var ParamYesterday = DateTime.Now.AddDays(-1);

            // Get the top 5 high scores since yesterday
            var HighScores = (from UserLog in DB.UserLogs
                              where UserLog.CountOfTurnsToWin != null
                              where UserLog.created > ParamYesterday
                              select UserLog)
                             .OrderBy(x => x.CountOfTurnsToWin)
                             .Take(5)
                             .ToList();

            // Create a response
            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            sb.Append("High Scores Today:\n\n");

            // Loop through each high score
            foreach (var Score in HighScores)
            {
                // Add the High Score to the response
                sb.Append(String.Format("Score: {0} - {1} - ({2} {3})\n\n"
                                        , Score.CountOfTurnsToWin
                                        , Score.WinnerUserName
                                        , Score.created.ToLocalTime().ToShortDateString()
                                        , Score.created.ToLocalTime().ToShortTimeString()));
            }

            // Create a reply message
            Activity replyToConversation = activity.CreateReply();

            replyToConversation.Recipient = activity.From;
            replyToConversation.Type      = "message";
            // Set the text containg the High Scores as the response
            replyToConversation.Text = sb.ToString();

            // Create a ConnectorClient and use it to send the reply message
            var connector =
                new ConnectorClient(new Uri(activity.ServiceUrl));

            // Send the reply
            connector.Conversations.SendToConversationAsync(replyToConversation);
        }
Esempio n. 4
0
        // Utility

        #region private async Task ShowHighScores(IDialogContext context, int paramDays)
        private async Task ShowHighScores(IDialogContext context, int paramDays)
        {
            // Get the High Scores
            Models.BotDataEntities DB = new Models.BotDataEntities();

            // Get Yesterday
            var ParamYesterday = DateTime.Now.AddDays(paramDays);

            var HighScores = (from UserLog in DB.UserLogs
                              where UserLog.CountOfTurnsToWin != null
                              where UserLog.created > ParamYesterday
                              select UserLog)
                             .OrderBy(x => x.CountOfTurnsToWin)
                             .Take(5)
                             .ToList();

            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            sb.Append("High Scores:\n\n");

            foreach (var Score in HighScores)
            {
                sb.Append(String.Format("Score: {0} - {1} - ({2} {3})\n\n"
                                        , Score.CountOfTurnsToWin
                                        , Score.WinnerUserName
                                        , Score.created.ToLocalTime().ToShortDateString()
                                        , Score.created.ToLocalTime().ToShortTimeString()));
            }

            // Create a reply message
            var resultMessage = context.MakeMessage();

            resultMessage.Type = "message";
            resultMessage.Text = sb.ToString();

            // Send Message
            await context.PostAsync(resultMessage);
        }
Esempio n. 5
0
        /// <summary>
        /// POST: api/Messages
        /// Receive a message from a user and reply to it
        /// </summary>
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            bool   boolAskedForUserName = false;
            string strUserName          = "";

            #region Set CurrentBaseURL and ChannelAccount
            // Get the base URL that this service is running at
            // This is used to show images
            string CurrentBaseURL =
                this.Url.Request.RequestUri.AbsoluteUri.Replace(@"api/messages", "");

            // Create an instance of BotData to store data
            BotData objBotData = new BotData();

            // Instantiate a StateClient to save BotData
            StateClient stateClient = activity.GetStateClient();

            // Use stateClient to get current userData
            BotData userData = await stateClient.BotState.GetUserDataAsync(
                activity.ChannelId, activity.From.Id);

            // Update userData by setting CurrentBaseURL and Recipient
            userData.SetProperty <string>("CurrentBaseURL", CurrentBaseURL);

            // Save changes to userData
            await stateClient.BotState.SetUserDataAsync(
                activity.ChannelId, activity.From.Id, userData);

            #endregion

            if (activity.Type == ActivityTypes.Message)
            {
                BotData leadData = stateClient.BotState.GetPrivateConversationData(
                    activity.ChannelId, activity.Conversation.Id, activity.From.Id);

                Models.BotDataEntities DB     = new Models.BotDataEntities();
                User          user            = DB.Users.FirstOrDefault(x => x.UserID == activity.From.Id);
                StringBuilder strReplyMessage = new StringBuilder();
                if (user == null)
                {
                    boolAskedForUserName = leadData.GetProperty <bool>("AskedForUserName");
                    strUserName          = leadData.GetProperty <string>("Email") ?? "";
                    // Create text for a reply message

                    if (boolAskedForUserName == false) // Never asked for email
                    {
                        strReplyMessage.Append(SR.Hello);
                        strReplyMessage.Append($"\n\n");
                        strReplyMessage.Append(SR.WhatEmail);

                        // Set BotUserData
                        leadData.SetProperty <bool>("AskedForUserName", true);
                    }
                    else // Have asked for email
                    {
                        string[] emailDomain = { "@pycogroup.com", "@pyramid-consulting", "@pyco.be", "@pyco-group.com" };
                        if (!emailDomain.Any(x => activity.Text.Contains(x))) // Name was never provided
                        {
                            // If we have asked for a username but it has not been set
                            // the current response is the user name
                            strReplyMessage.Append(SR.PycoEmailWrong);
                        }
                        else // Name was provided
                        {
                            string email = new EmailHelper().ExtractEmails(activity.Text);
                            leadData.SetProperty <string>("Email", email);
                            strReplyMessage.Append(string.Format(SR.OTPSend, email));
                            string newpass = SendOTP(activity, email);
                            user = new User()
                            {
                                Channel    = activity.ChannelId,
                                UserID     = activity.From.Id,
                                UserName   = activity.From.Name,
                                ExpiredOTP = DateTime.UtcNow.AddHours(1),
                                IsVerified = false,
                                Email      = email,
                                OTP        = newpass,
                                JoinDate   = DateTime.UtcNow
                            };
                            DB.Users.Add(user);
                            DB.SaveChanges();
                        }
                    }

                    // Save BotUserData
                    stateClient.BotState.SetPrivateConversationData(
                        activity.ChannelId, activity.Conversation.Id, activity.From.Id, leadData);

                    // Create a reply message
                    ConnectorClient connector    = new ConnectorClient(new Uri(activity.ServiceUrl));
                    Activity        replyMessage = activity.CreateReply(strReplyMessage.ToString());
                    await connector.Conversations.ReplyToActivityAsync(replyMessage);
                }
                else //check OTP is ok or user already authorize
                {
                    if (user.IsVerified)
                    {
                        await Conversation.SendAsync(activity, () => new ResourceDialog());
                    }
                    else
                    {
                        if (user.OTP == activity.Text && user.ExpiredOTP > DateTime.UtcNow)
                        {
                            //Update Database
                            user.IsVerified = true;
                            DB.Users.Attach(user);
                            DB.Entry(user).State = EntityState.Modified;
                            // other changed properties
                            DB.SaveChanges();
                            strReplyMessage.Append(SR.OTPValid);
                            strReplyMessage.Append(string.Format(SR.Welcome, activity.From.Name));
                            ConnectorClient connector    = new ConnectorClient(new Uri(activity.ServiceUrl));
                            Activity        replyMessage = activity.CreateReply(strReplyMessage.ToString());

                            // Call the CreateButtons utility method
                            // that will create 5 buttons to put on the Here Card
                            List <CardAction> cardButtons = UIControl.CreateButtons();

                            // Create a Hero Card and add the buttons
                            HeroCard plCard = new HeroCard()
                            {
                                Buttons = cardButtons
                            };

                            // Create an Attachment
                            // set the AttachmentLayout as 'list'
                            Microsoft.Bot.Connector.Attachment plAttachment = plCard.ToAttachment();
                            replyMessage.Attachments.Add(plAttachment);
                            replyMessage.AttachmentLayout = "list";


                            await connector.Conversations.ReplyToActivityAsync(replyMessage);
                        }
                        else if (user.OTP != activity.Text && user.ExpiredOTP > DateTime.UtcNow)
                        {
                            strReplyMessage.Append(SR.OTPWrong);
                            ConnectorClient connector    = new ConnectorClient(new Uri(activity.ServiceUrl));
                            Activity        replyMessage = activity.CreateReply(strReplyMessage.ToString());
                            await connector.Conversations.ReplyToActivityAsync(replyMessage);
                        }
                        else // OTP is wrong and expired
                        {
                            strReplyMessage.Append(SR.OTPInvalid);
                            DB.Users.Remove(user);
                            ConnectorClient connector    = new ConnectorClient(new Uri(activity.ServiceUrl));
                            Activity        replyMessage = activity.CreateReply(strReplyMessage.ToString());
                            await connector.Conversations.ReplyToActivityAsync(replyMessage);
                        }
                    }
                }
            }
            else
            {
                HandleSystemMessage(activity);
            }
            var response = Request.CreateResponse(HttpStatusCode.OK);
            return(response);
        }
Esempio n. 6
0
        public virtual async Task MessageReceivedAsync(
            IDialogContext context,
            IAwaitable <IMessageActivity> argument)
        {
            // Set BaseURL
            context.UserData.TryGetValue <string>(
                "CurrentBaseURL", out strBaseURL);

            int intGuessedNumber;

            // Get the text passed
            var message = await argument;

            // See if a number was passed
            if (!int.TryParse(message.Text, out intGuessedNumber))
            {
                // A number was not passed

                // Create a reply Activity
                Activity replyToConversation = (Activity)context.MakeMessage();
                replyToConversation.Recipient = replyToConversation.Recipient;
                replyToConversation.Type      = "message";

                string strNumberGuesserCard =
                    String.Format(@"{0}/{1}",
                                  strBaseURL,
                                  "Images/NumberGuesserCard.png?tick=123");

                List <CardImage> cardImages = new List <CardImage>();
                cardImages.Add(new CardImage(url: strNumberGuesserCard));

                // Create the Buttons
                // Call the CreateButtons utility method
                List <CardAction> cardButtons = CreateButtons();

                // Create the Hero Card
                // Set the image and the buttons
                HeroCard plCard = new HeroCard()
                {
                    Images  = cardImages,
                    Buttons = cardButtons,
                };

                // Create an Attachment by calling the
                // ToAttachment() method of the Hero Card
                Attachment plAttachment = plCard.ToAttachment();
                // Attach the Attachment to the reply
                replyToConversation.Attachments.Add(plAttachment);
                // set the AttachmentLayout as 'list'
                replyToConversation.AttachmentLayout = "list";

                // Send the reply
                // Create text for a reply message
                replyToConversation.Text = ($"Hello {message.From.Name}!.Below is simple game.Take it easy!");

                await context.PostAsync(replyToConversation);

                context.Wait(MessageReceivedAsync);
            }

            // This code will run when the user has entered a number
            if (int.TryParse(message.Text, out intGuessedNumber))
            {
                // A number was passed
                // See if it was the correct number
                if (intGuessedNumber != this.intNumberToGuess)
                {
                    // The number was not correct
                    this.intAttempts++;

                    // Create a response
                    // This time call the ** ShowButtons ** method
                    Activity replyToConversation =
                        ShowButtons(context, "Not correct. Guess again.");

                    // *************************
                    // Log to Database
                    // *************************

                    // Instantiate the BotData dbContext
                    Models.BotDataEntities DB = new Models.BotDataEntities();
                    // Create a new UserLog object
                    Models.UserLog NewUserLog = new Models.UserLog();

                    // Set the properties on the UserLog object
                    NewUserLog.Channel  = replyToConversation.ChannelId;
                    NewUserLog.UserID   = replyToConversation.From.Id;
                    NewUserLog.UserName = replyToConversation.From.Name;
                    NewUserLog.created  = DateTime.UtcNow;
                    // This logs the message being sent to the user
                    NewUserLog.Message = replyToConversation.Text.Truncate(500);

                    // Add the UserLog object to UserLogs
                    DB.UserLogs.Add(NewUserLog);
                    // Save the changes to the database
                    DB.SaveChanges();

                    await context.PostAsync(replyToConversation);

                    context.Wait(MessageReceivedAsync);
                }
                else
                {
                    // Game completed
                    StringBuilder sb = new StringBuilder();
                    sb.Append("Congratulations! ");
                    sb.Append("The number to guess was {0}. ");
                    sb.Append("You needed {1} attempts. ");
                    sb.Append("Would you like to play again?");

                    string CongratulationsStringPrompt =
                        string.Format(sb.ToString(),
                                      this.intNumberToGuess,
                                      this.intAttempts);

                    // *************************
                    // Log to Database
                    // *************************

                    // Create a reply Activity
                    Activity replyToConversation = (Activity)context.MakeMessage();

                    // Instantiate the BotData dbContext
                    Models.BotDataEntities DB = new Models.BotDataEntities();
                    // Create a new UserLog object
                    Models.UserLog NewUserLog = new Models.UserLog();

                    // Set the properties on the UserLog object
                    NewUserLog.Channel  = replyToConversation.ChannelId;
                    NewUserLog.UserID   = replyToConversation.From.Id;
                    NewUserLog.UserName = replyToConversation.From.Name;
                    NewUserLog.created  = DateTime.UtcNow;
                    // This logs the message being sent to the user
                    NewUserLog.Message = CongratulationsStringPrompt.Truncate(500);
                    // Log the number of turns it took to win
                    NewUserLog.CountOfTurnsToWin = this.intAttempts;
                    // Log the name of the user who won
                    NewUserLog.WinnerUserName = replyToConversation.Recipient.Name;

                    // Add the UserLog object to UserLogs
                    DB.UserLogs.Add(NewUserLog);
                    // Save the changes to the database
                    DB.SaveChanges();

                    // Put PromptDialog here
                    PromptDialog.Confirm(
                        context,
                        PlayAgainAsync,
                        CongratulationsStringPrompt,
                        "Didn't get that!");
                }
            }
        }
Esempio n. 7
0
        public virtual async Task MessageReceivedAsync(
            IDialogContext context,
            IAwaitable <IMessageActivity> argument)
        {
            // Set BaseURL
            context.UserData.TryGetValue <string>(
                "CurrentBaseURL", out strBaseURL);

            // Get the text passed
            var message = await argument;

            // See if a number was passed
            //if (!int.TryParse(message.Text, out intGuessedNumber))
            //{
            //    // A number was not passed

            //    // Create a reply Activity
            //    Activity replyToConversation = (Activity)context.MakeMessage();
            //    replyToConversation.Recipient = replyToConversation.Recipient;
            //    replyToConversation.Type = "message";

            //    string strLogo =
            //        String.Format(@"{0}/{1}",
            //        strBaseURL,
            //        "Images/Pycologo.png");

            //    List<CardImage> cardImages = new List<CardImage>();
            //    cardImages.Add(new CardImage(url: strLogo));

            //    // Create the Buttons
            //    // Call the CreateButtons utility method
            //    List<CardAction> cardButtons = CreateButtons();

            //    // Create the Hero Card
            //    // Set the image and the buttons
            //    HeroCard plCard = new HeroCard()
            //    {
            //        Images = cardImages,
            //        Buttons = cardButtons,
            //    };

            //    // Create an Attachment by calling the
            //    // ToAttachment() method of the Hero Card
            //    Attachment plAttachment = plCard.ToAttachment();
            //    // Attach the Attachment to the reply
            //    replyToConversation.Attachments.Add(plAttachment);
            //    // set the AttachmentLayout as 'list'
            //    replyToConversation.AttachmentLayout = "list";

            //    // Send the reply
            //    // Create text for a reply message
            //    replyToConversation.Text = string.Format(SR.Welcome, message.From.Name);

            //    await context.PostAsync(replyToConversation);
            //    context.Wait(MessageReceivedAsync);
            //}

            // This code will run when the user has entered a number
            if (Department.Contains(message.Text))
            {
                //this.Database.SqlQuery<YourEntityType>("storedProcedureName",params);
                Models.BotDataEntities DB    = new Models.BotDataEntities();
                string   deparment           = message.Text.Equals("HTML") ? "FE" : message.Text;
                var      resourceList        = DB.RESOURCE_VIEW.Where(x => x.STATUS == "On" && x.COMPANY == "Inhouse" && x.DEPTNAME == deparment).ToList();
                Activity replyToConversation = BuildResourceList(context, resourceList, deparment);

                await context.PostAsync(replyToConversation);

                context.Wait(MessageReceivedAsync);
            }
            else
            {
                // Create a response
                // This time call the ** ShowButtons ** method
                Activity replyToConversation = UIControl.
                                               ShowButtons(context, "It's not a department.Please choice again.");
                await context.PostAsync(replyToConversation);

                context.Wait(MessageReceivedAsync);
            }

            //if (int.TryParse(message.Text, out intGuessedNumber))
            //{
            //    // A number was passed
            //    // See if it was the correct number
            //    if (intGuessedNumber != this.intNumberToGuess)
            //    {
            //        // The number was not correct
            //        this.intAttempts++;

            //        // Create a response
            //        // This time call the ** ShowButtons ** method
            //        Activity replyToConversation =
            //            ShowButtons(context, "Not correct. Guess again.");



            //        await context.PostAsync(replyToConversation);
            //        context.Wait(MessageReceivedAsync);
            //    }
            //    else
            //    {
            //        // Game completed
            //        StringBuilder sb = new StringBuilder();
            //        sb.Append("Congratulations! ");
            //        sb.Append("The number to guess was {0}. ");
            //        sb.Append("You needed {1} attempts. ");
            //        sb.Append("Would you like to play again?");

            //        string CongratulationsStringPrompt =
            //            string.Format(sb.ToString(),
            //            this.intNumberToGuess,
            //            this.intAttempts);


            //        // Create a reply Activity
            //        Activity replyToConversation = (Activity)context.MakeMessage();


            //        // Put PromptDialog here
            //        PromptDialog.Confirm(
            //            context,
            //            PlayAgainAsync,
            //            CongratulationsStringPrompt,
            //            "Didn't get that!");
            //    }
            //}
        }