Ejemplo n.º 1
0
        private async Task ChooseNewTurn(IDialogContext context, IAwaitable <IMessageActivity> result)
        {
            var message = await result;
            int age;



            if (Int32.TryParse(message.Text, out age) && (age > 0))
            {
                await context.PostAsync($"Changed turn count to {age}.");

                context.Done(age);
            }
            else if ((--attempts) <= 0)
            {
                context.Fail(new TooManyAttemptsException("Message was not a valid whole number"));
            }
            else
            {
                await context.PostAsync("I didn't get that. I'm looking for whole numbers greater than 0 (e.g. '1', '30')");

                context.Wait(ChooseNewTurn);
            }
        }
Ejemplo n.º 2
0
        private async Task SelectTeam(IDialogContext context, IAwaitable <GraphServiceClient> result)
        {
            var graphServiceClient = await result;

            teams = await graphServiceClient.GetJoinedTeamsAsync();

            if (teams.Length == 0)
            {
                context.Fail(new Exception("Sorry. You do not belong to any team."));
            }
            else if (teams.Length == 1)
            {
                var team = teams.First();
                await context.SayAsync($"You only have one team: {team.DisplayName}. It was selected automatically.");

                context.Done(team);
            }
            else
            {
                await context.ChoiceAsync("Please select one of you teams", teams.Select(i => i.DisplayName));

                context.Wait(TeamSelected);
            }
        }
Ejemplo n.º 3
0
        private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> result)
        {
            var activity = await result;
            int caps;

            if (Int32.TryParse(activity.Text, out caps) && (caps > 0))
            {
                context.Done(caps);
            }
            else
            {
                --_attempts;
                if (_attempts > 0)
                {
                    await context.PostAsync("Я извиняюсь, но я не понял. Сколько выпил чашек (т.е. '1' или '2')?");

                    context.Wait(this.MessageReceivedAsync);
                }
                else
                {
                    context.Fail(new TooManyAttemptsException("Message was not a valid caps."));
                }
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Approves or Rejects an Approval.
        /// </summary>
        /// <param name="context">The <see cref="IDialogContext"/>.</param>
        /// <param name="result">The <see cref="IAwaitable{T}"/>.</param>
        /// <returns>An async <see cref="Task"/>/.</returns>
        public virtual async Task ApproveOrRejectAsync2(IDialogContext context, IAwaitable <IMessageActivity> result)
        {
            context.ThrowIfNull(nameof(context));
            result.ThrowIfNull(nameof(result));

            var activity = await result;
            var text     = activity.RemoveRecipientMention();

            var match = Regex.Match(text, CommandMatchApproveOrReject2);

            if (match.Success)
            {
                this.Account = match.Groups[3].Value;
                this.Profile = await this.GetValidatedProfile(context.UserData);

                this.TeamProject = match.Groups[4].Value;

                await this.ApproveOrRejectAsync(context, activity, $"{match.Groups[1].Value} {match.Groups[2].Value}");
            }
            else
            {
                context.Fail(new UnknownCommandException(activity.Text));
            }
        }
Ejemplo n.º 5
0
        private async Task MessageRecievedAsync(IDialogContext context, IAwaitable <IMessageActivity> result)
        {
            var message = await result;

            // Test if name is valid.
            if ((message.Text != null) && (message.Text.Trim().Length > 0))
            {
                context.Done(message.Text);
            }
            else
            {
                --attempts;
                if (attempts > 0)
                {
                    await context.PostAsync("I'm Sorry, I Dont understand your reply. What is your name ( e.g. 'Bill', 'Jc', 'Duke' )?");

                    context.Wait(this.MessageRecievedAsync);
                }
                else
                {
                    context.Fail(new TooManyAttemptsException("Message was not a string or was an empry string"));
                }
            }
        }
Ejemplo n.º 6
0
        public async Task CreateCuca(IDialogContext context)
        {
            var participants = new List <UserModel> {
                new UserModel {
                    Id = context.Activity.From.Id, Name = context.Activity.From.Name
                }
            };
            var cuca = new CucaModel {
                Date = dateToCreate.Value, Value = valueToCreate.Value, Participants = participants
            };

            try
            {
                var cucaCreated = await _cucaService.Create(cuca);

                context.Done(cucaCreated);
            }
            catch (Exception e)
            {
                await context.PostAsync($"Ocorreu um erro tente mais tarde {EmojiType.Cry}");

                context.Fail(e);
            }
        }
Ejemplo n.º 7
0
 public void Fail(Exception error)
 {
     _original.Fail(error);
 }
Ejemplo n.º 8
0
        private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> result)
        {
            var    message = await result;
            string dates   = message.Text.Trim();

            if ((message.Text != null) && (dates.Length == 2) && (dates[0] >= 48 && dates[0] <= 57) && (dates[1] >= 48 && dates[1] <= 57))
            {
                int exactDate = int.Parse(dates);

                if (exactDate >= 8 && exactDate <= 25)
                {
                    await context.PostAsync("You chose " + exactDate + "th. Please wait.");

                    //  데이터베이스에서 정보 끌어다놓기.
                    try
                    {
                        SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
                        builder.DataSource     = "pyeongchang.database.windows.net";
                        builder.UserID         = "hjs0579";
                        builder.Password       = "******";
                        builder.InitialCatalog = "PyeongChangDatabase";

                        using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
                        {
                            connection.Open();
                            StringBuilder sb = new StringBuilder();
                            sb.Append("SELECT * ");
                            sb.Append("FROM [dbo].[SportsInformation] ");
                            sb.Append("WHERE [Day] = " + exactDate);
                            String sql = sb.ToString();

                            using (SqlCommand command = new SqlCommand(sql, connection))
                            {
                                using (SqlDataReader reader = command.ExecuteReader())
                                {
                                    while (reader.Read())
                                    {
                                        await context.PostAsync("====================");

                                        await context.PostAsync("Sports: " + reader.GetString(0));

                                        await context.PostAsync("\nDescription: " + reader.GetString(1));

                                        await context.PostAsync("\nDate: " + reader.GetString(3) + "." + reader.GetString(4) + "." + reader.GetString(5));

                                        await context.PostAsync("\nDay of Week: " + reader.GetString(6));

                                        await context.PostAsync("\nStart Time: " + reader.GetString(7) + ":" + reader.GetString(8));

                                        await context.PostAsync("\nEnd Time: " + reader.GetString(9) + ":" + reader.GetString(10));

                                        await context.PostAsync("\nVenue: " + reader.GetString(11));
                                    }
                                    await context.PostAsync("====================");
                                }
                            }
                        }
                    }
                    catch (SqlException e)
                    {
                        Console.WriteLine(e.Message);
                        Console.WriteLine(e.Source);
                        Console.WriteLine(e.StackTrace);
                        Console.WriteLine(e.ToString());
                    }

                    context.Done(dates);
                }
                else
                {
                    --attempts;
                    if (attempts > 0)
                    {
                        await context.PostAsync("Available dates range from 8 to 25 days.");

                        await context.PostAsync("Please re-enter the desired date according to the format.e.g. 08 or 25");

                        context.Wait(this.MessageReceivedAsync);
                    }
                    else
                    {
                        context.Fail(new TooManyAttemptsException("You have entered too many incorrect messages."));
                    }
                }
            }
            else
            {
                --attempts;
                if (attempts > 0)
                {
                    await context.PostAsync("I didn't understand");

                    await context.PostAsync("Please re-enter the desired date according to the format.e.g. 08 or 25");

                    context.Wait(this.MessageReceivedAsync);
                }
                else
                {
                    context.Fail(new TooManyAttemptsException("You have entered too many incorrect messages."));
                }
            }
        }
Ejemplo n.º 9
0
 public async Task StartAsync(IDialogContext context)
 {
     context.Fail(new NotImplementedException("Данная функция еще не поддерживается"));
 }
Ejemplo n.º 10
0
 public async Task StartAsync(IDialogContext context)
 {
     context.Fail(new NotImplementedException("Hard Test is not implemented :D"));
 }
Ejemplo n.º 11
0
        //TODO: Validation; Too many if statements
        //DONE: Typing support
        private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> result)
        {
            var     message         = await result;
            Account selectedAccount = null;

            //Check message and respond with action
            if (message.Value != null)
            {
                try
                {
                    selectedAccount = JsonConvert.DeserializeObject <Account>(message.Value.ToString());
                }
                catch (JsonException e)
                {
                    Console.WriteLine(e.Message);
                }
            }
            else if (!string.IsNullOrEmpty(message.Text))
            {
                //Check if user typed name of account instead.
                foreach (var account in _accounts)
                {
                    if (string.Equals(account.Name, message.Text, StringComparison.CurrentCultureIgnoreCase))
                    {
                        selectedAccount = account;
                        break;
                    }

                    //TODO: Use scorables to handle 'quit'
                    if (message.Text == "quit")
                    {
                        context.Fail(new Exception("User quit"));
                        return;
                    }
                }
            }

            if (selectedAccount != null)
            {
                if (_saveGlobally)
                {
                    context.ConversationData.SetValue(DataStrings.ActiveAccount, selectedAccount);
                }

                //await context.PostAsync($"{selectedAccount.Name} selected");
                context.Done(selectedAccount);
            }
            else
            {
                var options = string.Empty;

                foreach (var account in _accounts)
                {
                    options += $"* {account.Name}  \n";
                }

                await context.PostAsync($"Sorry, no account with that name. Options are:\n{options}\n\nPlease try again");

                context.Wait(MessageReceivedAsync);
            }
        }
Ejemplo n.º 12
0
 public async Task StartAsync(IDialogContext context)
 {
     context.Fail(new NotImplementedException("Flights dialog is in development please stand by"));
 }
Ejemplo n.º 13
0
 public async Task StartAsync(IDialogContext context)
 {
     context.Fail(new NotImplementedException("Flights Dialog is not implemented and is instead being used to show context.Fail"));
 }
        private async Task MessageReceivedAsync2(IDialogContext context, IAwaitable <IMessageActivity> result)
        {
            var    message = await result;
            string times   = message.Text.Trim();

            if ((message.Text != null) && (times.Length == 5) && (times[0] >= 48 && times[0] <= 50) && (times[1] >= 48 && times[1] <= 57) && (times[3] >= 48 && times[3] <= 50) && (times[4] >= 48 && times[4] <= 57) && times[2] == '-')
            {
                int exactDate1 = 10 * (times[0] - 48) + (times[1] - 48);
                int exactDate2 = 10 * (times[3] - 48) + (times[4] - 48);

                if ((exactDate1 >= 0 && exactDate1 <= 24) && (exactDate2 >= 0 && exactDate2 <= 24))
                {
                    if (exactDate1 > exactDate2)
                    {
                        int i = exactDate1;
                        exactDate1 = exactDate2;
                        exactDate2 = i;
                    }

                    real_time1 = exactDate1;
                    real_time2 = exactDate2;

                    await context.PostAsync("You chose from " + real_time1 + ":00 to" + real_time2 + ":00. Please wait.");

                    // 데이터베이스 입력
                    try
                    {
                        SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
                        builder.DataSource     = "pyeongchang.database.windows.net";
                        builder.UserID         = "hjs0579";
                        builder.Password       = "******";
                        builder.InitialCatalog = "PyeongChangDatabase";

                        using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
                        {
                            Console.WriteLine("\nQuery data example:");
                            Console.WriteLine("=========================================\n");

                            connection.Open();
                            StringBuilder sb = new StringBuilder();
                            sb.Append("SELECT * ");
                            sb.Append("FROM [dbo].[SportsInformation] ");
                            sb.Append("WHERE [Day] = " + real_date + "and [StartTime_H] >= " + real_time1 + "and [EndTime_H] < " + real_time2);
                            String sql = sb.ToString();

                            using (SqlCommand command = new SqlCommand(sql, connection))
                            {
                                using (SqlDataReader reader = command.ExecuteReader())
                                {
                                    while (reader.Read())
                                    {
                                        await context.PostAsync("====================");

                                        await context.PostAsync("Sports: " + reader.GetString(0));

                                        await context.PostAsync("\nDescription: " + reader.GetString(1));

                                        await context.PostAsync("\nDate: " + reader.GetString(3) + "." + reader.GetString(4) + "." + reader.GetString(5));

                                        await context.PostAsync("\nDay of Week: " + reader.GetString(6));

                                        await context.PostAsync("\nStart Time: " + reader.GetString(7) + ":" + reader.GetString(8));

                                        await context.PostAsync("\nEnd Time: " + reader.GetString(9) + ":" + reader.GetString(10));

                                        await context.PostAsync("\nVenue: " + reader.GetString(11));
                                    }
                                    await context.PostAsync("====================");
                                }
                            }
                        }
                    }
                    catch (SqlException e)
                    {
                        Console.WriteLine(e.Message);
                        Console.WriteLine(e.Source);
                        Console.WriteLine(e.StackTrace);
                        Console.WriteLine(e.ToString());
                    }

                    context.Done(times);
                }
                else
                {
                    --attempts;
                    if (attempts > 0)
                    {
                        await context.PostAsync("Available dates range from 00:00 to 24:00");

                        await context.PostAsync("Please re-enter the desired time.");

                        await context.PostAsync("You can only select in hours. Please type according to the format. E.g. 01 - 23");

                        context.Wait(this.MessageReceivedAsync2);
                    }
                    else
                    {
                        context.Fail(new TooManyAttemptsException("You have entered too many incorrect messages."));
                    }
                }
            }
            else
            {
                --attempts;
                if (attempts > 0)
                {
                    await context.PostAsync("I didn't understand");

                    await context.PostAsync("Please re-enter the desired time.");

                    await context.PostAsync("You can only select in hours. Please type according to the format. E.g. 01 - 23");

                    context.Wait(this.MessageReceivedAsync2);
                }
                else
                {
                    context.Fail(new TooManyAttemptsException("You have entered too many incorrect messages."));
                }
            }
        }
Ejemplo n.º 15
0
        private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> result)
        {
            string  currencyNameOrSymbol = string.Empty;
            decimal currencyMultiplier   = 1.0m;

            // Message forwarded from luis or not
            if (_luisResult == null)
            {
                var      message  = await result;
                string[] entities = message.Text.Split(default(string[]), StringSplitOptions.RemoveEmptyEntries);

                // If input contains currencyMultiplier and currencyNameOrSymbol
                if (entities.Length < 2)
                {
                    context.Fail(new ArgumentException("Sorry i can't recognize value and currency (command should look like *Remove 1.0 BTC*)."));
                }
                else
                {
                    decimal.TryParse(entities[0], out currencyMultiplier);
                    currencyNameOrSymbol = entities[1];
                }
            }
            else
            {
                foreach (var entity in _luisResult.Entities)
                {
                    if (entity.Type == "Currency.Multiplier" && entity.Entity != null)
                    {
                        decimal.TryParse(entity.Entity.Replace(" ", String.Empty), out currencyMultiplier);
                    }

                    if (entity.Type == "Currency.Symbol" && entity.Entity != null)
                    {
                        currencyNameOrSymbol = entity.Entity;
                    }

                    if (entity.Type == "Currency.Name" && entity.Entity != null)
                    {
                        currencyNameOrSymbol = entity.Entity;
                    }
                }
            }

            // Final input checking
            if (currencyMultiplier > 0.0m && currencyNameOrSymbol != null && !string.IsNullOrWhiteSpace(currencyNameOrSymbol))
            {
                var currency = _service.GetCurrencyByNameOrSymbol(currencyNameOrSymbol);

                if (currency != null)
                {
                    currency.Multiplier = currencyMultiplier;
                    bool portfolioContainsCurrency = _service.IsCurrencyInPortfolio(currency);
                    if (portfolioContainsCurrency)
                    {
                        _service.RemoveCurrencyFromPortfolio(currency);
                        context.Done("Portfolio successfully updated!");
                    }
                    else
                    {
                        context.Fail(new ArgumentException("Sorry i can't find that currency in your portfolio."));
                    }
                }
            }
            else
            {
                context.Fail(new ArgumentException("Sorry i can't recognize value and currency (e.g. 1.0 BTC)."));
            }
        }
Ejemplo n.º 16
0
        private async Task ResumeArticleSearchDialog(IDialogContext context, IAwaitable <ArticleSearchQuery> result)
        {
            try
            {
                var    resultFromArticleSearch = await result;
                string _strhelpArticle         = Convert.ToString(resultFromArticleSearch.HelpArticle);
                int    _iLearningMaterial      = Convert.ToInt32(resultFromArticleSearch.LearningMaterial);

                try
                {
                    SharePointPrimary             obj          = new SharePointPrimary();
                    Dictionary <ListItem, string> searchedDocs = new Dictionary <ListItem, string>();

                    if (_iLearningMaterial == 2)
                    {
                        searchedDocs = obj.SearchLearningVideoByTopic(_strhelpArticle);
                        if (searchedDocs.Count > 0)
                        {
                            if (searchedDocs.Count == 1)
                            {
                                await context.PostAsync($"I have found {searchedDocs.Count} video on your search topic \U0001F44D ");
                            }
                            else
                            {
                                await context.PostAsync($"I have found {searchedDocs.Count} videos on your search topic \U0001F44D ");
                            }

                            foreach (var eachDoc in searchedDocs)
                            {
                                try
                                {
                                    var videoCard = new VideoCard();
                                    videoCard.Title    = eachDoc.Key.FieldValuesAsHtml["Title"];
                                    videoCard.Subtitle = eachDoc.Key.FieldValuesAsHtml["SubTitle"];
                                    videoCard.Text     = eachDoc.Key.FieldValuesAsHtml["VideoSetDescription"];

                                    string _previewImageBase64 = obj.GetImage(eachDoc.Key.FieldValuesAsText["AlternateThumbnailUrl"].Split(',')[0].ToString(), _iLearningMaterial);


                                    if (!string.IsNullOrEmpty(_previewImageBase64))
                                    {
                                        videoCard.Image = new ThumbnailUrl(
                                            url: _previewImageBase64,
                                            alt: "Learning Video");
                                    }

                                    //string _videoBase64 = obj.GetVideo("https://avaindcollabsl.sharepoint.com/sites/SOHA_HelpRepository/VideoRepository/Build%20a%20Chat%20Bot%20with%20Azure%20Bot%20Service/buildachatbotwithazurebotservice_high.mp4");

                                    //string _videoBase64 = obj.GetVideo(eachDoc.Value);


                                    if (!string.IsNullOrEmpty(eachDoc.Value))
                                    {
                                        videoCard.Media = new List <MediaUrl> {
                                            new MediaUrl("https://sec.ch9.ms/ch9/a7a4/10df13cf-a7ac-40a2-b713-6fcc935ba7a4/buildachatbotwithazurebotservice.mp4")
                                        };

                                        videoCard.Buttons = new List <CardAction> {
                                            new CardAction(
                                                type: ActionTypes.OpenUrl,
                                                title: "Learn more",
                                                value: "https://channel9.msdn.com/Blogs/MVP-Azure/build-a-chatbot-with-azure-bot-service")
                                        };
                                    }


                                    //if (!string.IsNullOrEmpty(/*eachDoc.Value*/_videoBase64))
                                    //{
                                    //    videoCard.Media = new List<MediaUrl> { new MediaUrl(_videoBase64) };

                                    //    videoCard.Buttons = new List<CardAction> { new CardAction(
                                    //    type  : ActionTypes.OpenUrl,
                                    //    title : "Learn more",
                                    //    value : eachDoc.Value) };
                                    //}

                                    Microsoft.Bot.Connector.Attachment attachment = new Microsoft.Bot.Connector.Attachment();
                                    var replyMessage = context.MakeMessage();
                                    attachment = videoCard.ToAttachment();
                                    replyMessage.Attachments.Add(attachment);

                                    await context.PostAsync(replyMessage);
                                }
                                catch (Exception ex)
                                {
                                    await context.PostAsync(ex.Message);
                                }
                            }

                            await context.PostAsync("Hope you have found the result informative. Do you want to search for any other topic?");

                            context.Wait(MessageReceived);
                        }
                        else
                        {
                            await context.PostAsync($"No video found. Do you want to search for any other topic?");

                            context.Wait(MessageReceived);
                        }
                    }
                    else if (_iLearningMaterial == 1)
                    {
                        searchedDocs = obj.SearchHelpArticleonTopic(_strhelpArticle);
                        if (searchedDocs.Count > 0)
                        {
                            if (searchedDocs.Count == 1)
                            {
                                await context.PostAsync($"I have found {searchedDocs.Count} article on your search topic \U0001F44D ");
                            }
                            else
                            {
                                await context.PostAsync($"I have found {searchedDocs.Count} articles on your search topic \U0001F44D ");
                            }

                            foreach (var eachDoc in searchedDocs)
                            {
                                Microsoft.Bot.Connector.Attachment attachment = new Microsoft.Bot.Connector.Attachment();

                                var replyMessage = context.MakeMessage();

                                var heroCard = new HeroCard();

                                string _previewImageBase64 = obj.GetImage(eachDoc.Value.ToString(), _iLearningMaterial);

                                heroCard.Title    = eachDoc.Key.DisplayName;
                                heroCard.Subtitle = "by Avanade Collab SL Capability";
                                heroCard.Text     = eachDoc.Key.FieldValuesAsHtml["KpiDescription"];
                                heroCard.Buttons  = new List <CardAction> {
                                    new CardAction(ActionTypes.OpenUrl, "Read more", value: Constants.RootSiteCollectionURL + eachDoc.Key.File.ServerRelativeUrl)
                                };

                                if (!string.IsNullOrEmpty(_previewImageBase64))
                                {
                                    heroCard.Images = new List <CardImage> {
                                        new CardImage(_previewImageBase64)
                                    }
                                }
                                ;


                                attachment = heroCard.ToAttachment();
                                replyMessage.Attachments.Add(attachment);

                                await context.PostAsync(replyMessage);
                            }

                            await context.PostAsync("Hope you have found the result informative. Do you want to search for any other topic?");

                            context.Wait(MessageReceived);
                        }
                        else
                        {
                            await context.PostAsync($"No document found. Do you want to search for any other topic?");

                            context.Wait(MessageReceived);
                        }
                    }
                }
                catch (TooManyAttemptsException)
                {
                    context.Fail(new TooManyAttemptsException("Unable to find any help document."));
                }
            }
            catch (TooManyAttemptsException)
            {
                await context.PostAsync("Sorry \U0001F641 , I am unable to understand you. Let us try again.");
            }
        }
Ejemplo n.º 17
0
        private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> result)
        {
            var    message = await result;
            string dates   = message.Text.Trim();

            if ((message.Text != null) && (dates.Length == 2) && (dates[0] >= 48 && dates[0] <= 57) && (dates[1] >= 48 && dates[1] <= 57))
            {
                int exactDate = int.Parse(dates);

                if (exactDate >= 8 && exactDate <= 25)
                {
                    await context.PostAsync(exactDate + "일을 선택하였습니다. 잠시만 기다려주세요.");

                    //  데이터베이스에서 정보 끌어다놓기.
                    try
                    {
                        SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
                        builder.DataSource     = "pyeongchang.database.windows.net";
                        builder.UserID         = "hjs0579";
                        builder.Password       = "******";
                        builder.InitialCatalog = "PyeongChangDatabase";

                        using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
                        {
                            Console.WriteLine("\nQuery data example:");
                            Console.WriteLine("=========================================\n");

                            connection.Open();
                            StringBuilder sb = new StringBuilder();
                            sb.Append("SELECT * ");
                            sb.Append("FROM [dbo].[SportsInformation] ");
                            sb.Append("WHERE [Day] = " + exactDate);
                            String sql = sb.ToString();

                            using (SqlCommand command = new SqlCommand(sql, connection))
                            {
                                using (SqlDataReader reader = command.ExecuteReader())
                                {
                                    while (reader.Read())
                                    {
                                        await context.PostAsync(
                                            "Sports: " + reader.GetString(0) +
                                            "\nDescription: " + reader.GetString(1) +
                                            "\nDate: " + reader.GetString(3) + "." + reader.GetString(4) + "." + reader.GetString(5) +
                                            "\nDay of Week: " + reader.GetString(6) +
                                            "\nStart Time: " + reader.GetString(7) + ":" + reader.GetString(8) +
                                            "\nEnd Time: " + reader.GetString(9) + ":" + reader.GetString(10) +
                                            "\nVenue: " + reader.GetString(11));
                                    }
                                }
                            }
                        }
                    }
                    catch (SqlException e)
                    {
                        Console.WriteLine(e.Message);
                        Console.WriteLine(e.Source);
                        Console.WriteLine(e.StackTrace);
                        Console.WriteLine(e.ToString());
                    }

                    context.Done(dates);
                }
                else
                {
                    --attempts;
                    if (attempts > 0)
                    {
                        await context.PostAsync("선택 가능한 날짜는 8일부터 25일까지입니다. 형식에 맞게 원하시는 날짜를 다시 입력해주세요. e.g. 08 or 25");

                        context.Wait(this.MessageReceivedAsync);
                    }
                    else
                    {
                        context.Fail(new TooManyAttemptsException("너무 많이 잘못된 메시지를 입력하였습니다."));
                    }
                }
            }
            else
            {
                --attempts;
                if (attempts > 0)
                {
                    await context.PostAsync("이해하지 못하였습니다. 형식에 맞게 원하시는 날짜를 다시 입력해주세요. e.g. 08 or 25");

                    context.Wait(this.MessageReceivedAsync);
                }
                else
                {
                    context.Fail(new TooManyAttemptsException("너무 많이 잘못된 메시지를 입력하였습니다."));
                }
            }
        }
Ejemplo n.º 18
0
        private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <object> result)
        {
            var    activity = await result as Activity;
            string msg      = activity.Text.Trim().ToLower();

            if (msg == "start over" || msg == "exit" || msg == "quit" || msg == "done" || msg == "start again" || msg == "restart" || msg == "leave" || msg == "reset" || msg == "bye" || msg == "goodbye")
            {
                context.PrivateConversationData.Clear();
                await context.PostAsync($"Ending your session...Dont' forget to delete your conversation for privacy!");

                context.Done("");
            }
            else
            {
                model.Patient pat = null;
                // Within the code body set your variable
                string     fhirserver       = CloudConfigurationManager.GetSetting("FHIRServerAddress");
                string     fhirtenant       = CloudConfigurationManager.GetSetting("FHIRAADTenant");
                string     fhirclientid     = CloudConfigurationManager.GetSetting("FHIRClientId");
                string     fhirclientsecret = CloudConfigurationManager.GetSetting("FHIRClientSecret");
                FHIRClient fhirclient       = new FHIRClient(fhirserver, fhirtenant, fhirclientid, fhirclientsecret);
                var        rslt             = (model.Bundle)fhirclient.LoadResource("Patient", "identifier=http://fhirbot.org|" + activity.Text.Trim());
                if (rslt != null && rslt.Entry != null && rslt.Entry.Count > 0)
                {
                    pat = (model.Patient)rslt.Entry.FirstOrDefault().Resource;
                    if (pat != null)
                    {
                        var fbid = pat.Identifier.Single(ident => ident.System == "http://fhirbot.org");
                        if (fbid != null)
                        {
                            var period = fbid.Period;
                            var now    = model.FhirDateTime.Now();
                            if (period != null && (now > period.EndElement))
                            {
                                //Use Period Expired remove the token from the patient and update db
                                pat.Identifier.Remove(fbid);
                                fhirclient.SaveResource(pat);
                                pat = null;
                                context.PrivateConversationData.Clear();
                            }
                        }
                    }
                }
                if (pat != null)
                {
                    // Set BotUserData
                    context.PrivateConversationData.SetValue <string>(
                        "id", pat.Id);
                    context.PrivateConversationData.SetValue <string>(
                        "name", pat.Name[0].Text);
                    context.PrivateConversationData.SetValue <DateTime?>(
                        "sessionstart", DateTime.Now);
                    context.PrivateConversationData.SetValue <string>("bearertoken", fhirclient.BearerToken);
                    context.PrivateConversationData.SetValue <string>("fhirserver", fhirserver);
                    context.Done(pat.Name[0].Text);
                }
                else
                {
                    context.Fail(new InvalidPINException("Not a valid PIN Code"));
                }
            }
        }
Ejemplo n.º 19
0
        private async Task MessageReceived(IDialogContext context, IAwaitable <object> result)
        {
            Activity activity = (Activity)context.Activity;

            if (activity.Text == "quit")
            {
                context.Fail(new OperationCanceledException("You cancelled the operation."));
                return;
            }

            var oauthClient = activity.GetOAuthClient();
            var token       = await oauthClient.OAuthApi.GetUserTokenAsync(activity.From.Id, ConnectionName).ConfigureAwait(false);

            if (token != null)
            {
                await context.PostAsync($"You are already signed in.");

                context.Done(this._entities);
            }
            else
            {
                // see if the user is pending a login, if so, try to take the validation code and exchange it for a token
                bool ActiveSignIn = false;
                if (context.UserData.ContainsKey("ActiveSignIn"))
                {
                    ActiveSignIn = context.UserData.GetValue <bool>("ActiveSignIn");
                }

                if (!ActiveSignIn)
                {
                    // If the bot is not waiting for the user to sign in, ask them to do so
                    await context.PostAsync("Hello! Let's get you signed in!");

                    // Send an OAuthCard to get the user signed in
                    var oauthReply = await activity.CreateOAuthReplyAsync(ConnectionName, "Please sign in", "Sign in").ConfigureAwait(false);

                    await context.PostAsync(oauthReply);

                    // Save some state saying an Active sign in is in progress for this user
                    context.UserData.SetValue <bool>("ActiveSignIn", true);
                }
                else
                {
                    await context.PostAsync("Let's see if that code works...");

                    // try to exchange the message text for a token
                    token = await oauthClient.OAuthApi.GetUserTokenAsync(activity.From.Id, ConnectionName, magicCode : activity.Text).ConfigureAwait(false);

                    if (token != null)
                    {
                        await context.PostAsync($"It worked! You are now signed in");

                        // The sign in is complete so set state to note that
                        context.UserData.SetValue <bool>("ActiveSignIn", true);
                        context.Done(this._entities);
                    }
                    else
                    {
                        attempts--;
                        if (attempts > 0)
                        {
                            await context.PostAsync($"Hmm, that code wasn't right.");

                            context.Wait(this.MessageReceived);
                        }
                        else
                        {
                            context.Fail(new TooManyAttemptsException("I think the code you're trying is wrong. Ask \"Sign in\" to try again from the start."));
                        }
                    }
                }
            }
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Gets a list of subscriptions for the user.
        /// </summary>
        /// <param name="context">A <see cref="IDialogContext"/>.</param>
        /// <param name="result">A <see cref="IMessageActivity"/>.</param>
        /// <returns>A <see cref="Task"/>.</returns>
        public async Task SubscriptionsAsync(IDialogContext context, IAwaitable <IMessageActivity> result)
        {
            context.ThrowIfNull(nameof(context));
            result.ThrowIfNull(nameof(result));

            var activity = await result;

            var text = (activity.Text ?? string.Empty).Trim().ToLowerInvariant();

            if (text.Equals(CommandMatchSubscriptions, StringComparison.OrdinalIgnoreCase))
            {
                var data = context.UserData.GetValue <UserData>("userData");

                this.Account = data.Account;
                this.Profile = await this.GetValidatedProfile(context.UserData);

                this.TeamProject = data.TeamProject;

                var typing = context.MakeMessage();
                typing.Type = ActivityTypes.Typing;
                await context.PostAsync(typing);

                var querySpec = new SqlQuerySpec
                {
                    QueryText  = "SELECT * FROM subscriptions s WHERE s.channelId = @channelId AND s.userId = @userId",
                    Parameters = new SqlParameterCollection
                    {
                        new SqlParameter("@channelId", activity.ChannelId),
                        new SqlParameter("@userId", activity.From.Id)
                    }
                };

                var storedSubs = this.documentClient
                                 .CreateDocumentQuery <Subscription>(UriFactory.CreateDocumentCollectionUri("botdb", "subscriptioncollection"), querySpec)
                                 .ToList();

                var subscriptions = Enum
                                    .GetValues(typeof(SubscriptionType))
                                    .Cast <SubscriptionType>()
                                    .Where(e => storedSubs.All(s => s.SubscriptionType != e))
                                    .Select(e => new Subscription {
                    SubscriptionType = e, ChannelId = activity.ChannelId, ProfileId = this.Profile.Id, UserId = activity.From.Id
                });

                var cards = storedSubs
                            .Union(subscriptions)
                            .OrderBy(s => s.SubscriptionType)
                            .Select(s => new SubscriptionCard(s, this.TeamProject))
                            .ToList();

                var reply = context.MakeMessage();
                foreach (var card in cards)
                {
                    reply.Attachments.Add(card);
                }

                reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                await context.PostAsync(reply);

                context.Wait(this.SubscribeAsync);
            }
            else
            {
                context.Fail(new UnknownCommandException(activity.Text));
            }
        }
Ejemplo n.º 21
0
 public async Task StartAsync(IDialogContext context)
 {
     context.Fail(new NotImplementedException("ops"));
 }
 public void Fail(Exception error)
 {
     context.Fail(error);
 }
Ejemplo n.º 23
0
        /// <summary>
        /// Subscribes to a subscribtion.
        /// </summary>
        /// <param name="context">A <see cref="IDialogContext"/>.</param>
        /// <param name="result">A <see cref="IMessageActivity"/>.</param>
        /// <returns>A <see cref="Task"/>.</returns>
        public async Task SubscribeAsync(IDialogContext context, IAwaitable <IMessageActivity> result)
        {
            context.ThrowIfNull(nameof(context));
            result.ThrowIfNull(nameof(result));

            var activity = await result;
            var text     = (activity.RemoveRecipientMention() ?? string.Empty).ToLowerInvariant().Trim();
            var reply    = context.MakeMessage();

            var matchSubscribe   = Regex.Match(text, CommandMatchSubscribe);
            var matchUnsubscribe = Regex.Match(text, CommandMatchUnsubscribe);

            if (matchSubscribe.Success || matchUnsubscribe.Success)
            {
                var typing = context.MakeMessage();
                typing.Type = ActivityTypes.Typing;
                await context.PostAsync(typing);
            }

            if (matchSubscribe.Success)
            {
                var subscriptionType      = (SubscriptionType)Enum.Parse(typeof(SubscriptionType), matchSubscribe.Groups[1].Value, true);
                var subscriptionTypeTitle = Labels.ResourceManager.GetString("SubscriptionShortTitle_" + subscriptionType);
                var querySpec             = new SqlQuerySpec
                {
                    QueryText  = "SELECT * FROM subscriptions s WHERE s.channelId = @channelId AND s.userId = @userId AND s.subscriptionType = @subscriptionType",
                    Parameters = new SqlParameterCollection
                    {
                        new SqlParameter("@channelId", activity.ChannelId),
                        new SqlParameter("@userId", activity.From.Id),
                        new SqlParameter("@subscriptionType", subscriptionType)
                    }
                };

                var subscription = this.documentClient
                                   .CreateDocumentQuery <Subscription>(UriFactory.CreateDocumentCollectionUri("botdb", "subscriptioncollection"), querySpec)
                                   .ToList()
                                   .FirstOrDefault();

                if (subscription != null)
                {
                    context.Done(reply);
                    return;
                }

                var teamProjects = await this.VstsService.GetProjects(this.Account, this.Profile.Token);

                var teamProject = teamProjects.FirstOrDefault(tp => tp.Name.Equals(this.TeamProject, StringComparison.OrdinalIgnoreCase));

                if (teamProject == null)
                {
                    context.Done(reply);
                    return;
                }

                subscription = new Subscription
                {
                    BotId            = activity.Recipient.Id,
                    BotName          = activity.Recipient.Name,
                    ChannelId        = activity.ChannelId,
                    IsActive         = true,
                    ProfileId        = this.Profile.Id,
                    RecipientId      = activity.From.Id,
                    ServiceUri       = new Uri(activity.ServiceUrl),
                    SubscriptionType = subscriptionType,
                    TenantId         = activity.ChannelId.Equals(ChannelIds.Msteams) ? activity.GetTenantId() : string.Empty,
                    UserId           = activity.From.Id
                };

                var strategy = this.strategies.First(s => s.CanGetSubscription(subscriptionType));
                var s2       = strategy.GetSubscription(subscription.Id, teamProject);

                var r = await this.VstsService.CreateSubscription(this.Account, s2, this.Profile.Token);

                subscription.IdentityId     = r.CreatedBy.Id;
                subscription.SubscriptionId = r.Id;

                await this.documentClient.UpsertDocumentAsync(
                    UriFactory.CreateDocumentCollectionUri("botdb", "subscriptioncollection"), subscription);

                reply.Text = string.Format(Labels.Subscribed, subscriptionTypeTitle);

                await context.PostAsync(reply);

                context.Done(reply);
            }
            else if (matchUnsubscribe.Success)
            {
                var subscriptionType      = (SubscriptionType)Enum.Parse(typeof(SubscriptionType), matchUnsubscribe.Groups[1].Value, true);
                var subscriptionTypeTitle = Labels.ResourceManager.GetString("SubscriptionShortTitle_" + subscriptionType);
                var querySpec             = new SqlQuerySpec
                {
                    QueryText  = "SELECT * FROM subscriptions s WHERE s.channelId = @channelId AND s.userId = @userId AND s.subscriptionType = @subscriptionType",
                    Parameters = new SqlParameterCollection
                    {
                        new SqlParameter("@channelId", activity.ChannelId),
                        new SqlParameter("@userId", activity.From.Id),
                        new SqlParameter("@subscriptionType", subscriptionType)
                    }
                };

                var subscription = this.documentClient
                                   .CreateDocumentQuery <Document>(UriFactory.CreateDocumentCollectionUri("botdb", "subscriptioncollection"), querySpec)
                                   .ToList()
                                   .FirstOrDefault();

                if (subscription != null)
                {
                    await this.documentClient.DeleteDocumentAsync(subscription.SelfLink);

                    await this.VstsService.DeleteSubscription(this.Account, subscription.GetPropertyValue <Guid>("subscriptionId"), this.Profile.Token);

                    reply.Text = string.Format(Labels.Unsubscribed, subscriptionTypeTitle);
                    await context.PostAsync(reply);
                }

                context.Done(reply);
            }
            else
            {
                context.Fail(new UnknownCommandException(activity.Text));
            }
        }
        private async Task MessageReceivedAsync2(IDialogContext context, IAwaitable <IMessageActivity> result)
        {
            var    message = await result;
            string times   = message.Text.Trim();

            if ((message.Text != null) && (times.Length == 5) && (times[0] >= 48 && times[0] <= 50) && (times[1] >= 48 && times[1] <= 57) && (times[3] >= 48 && times[3] <= 50) && (times[4] >= 48 && times[4] <= 57) && times[2] == '-')
            {
                int exactDate1 = 10 * (times[0] - 48) + (times[1] - 48);
                int exactDate2 = 10 * (times[3] - 48) + (times[4] - 48);

                if ((exactDate1 >= 0 && exactDate1 <= 24) && (exactDate2 >= 0 && exactDate2 <= 24))
                {
                    if (exactDate1 > exactDate2)
                    {
                        int i = exactDate1;
                        exactDate1 = exactDate2;
                        exactDate2 = i;
                    }

                    real_time1 = exactDate1;
                    real_time2 = exactDate2;

                    await context.PostAsync(real_time1 + "시부터 " + real_time2 + "시까지를 선택하였습니다. 잠시만 기다려주세요.");



                    // 데이터베이스 입력



                    context.Done(times);
                }
                else
                {
                    --attempts;
                    if (attempts > 0)
                    {
                        await context.PostAsync("선택 가능한 시간은 00시부터 24시까지입니다. 원하는 시간 범위를 다시 입력해주세요. 시 단위로만 선택 가능하며 선택 가능한 시간은 00시부터 24시까지입니다. 형식에 맞게 입력해주세요. e.g. 01-23");

                        context.Wait(this.MessageReceivedAsync2);
                    }
                    else
                    {
                        context.Fail(new TooManyAttemptsException("너무 많이 잘못된 메시지를 입력하였습니다."));
                    }
                }
            }
            else
            {
                --attempts;
                if (attempts > 0)
                {
                    await context.PostAsync("이해하지 못하였습니다. 원하는 시간 범위를 다시 입력해주세요. 시 단위로만 선택 가능하며 선택 가능한 시간은 00시부터 24시까지입니다. 형식에 맞게 입력해주세요. e.g. 01-23");

                    context.Wait(this.MessageReceivedAsync2);
                }
                else
                {
                    context.Fail(new TooManyAttemptsException("너무 많이 잘못된 메시지를 입력하였습니다."));
                }
            }
        }
Ejemplo n.º 25
0
        private async Task ResumeExternalSharingDialog(IDialogContext context, IAwaitable <ExternalSharingQuery> result)
        {
            try
            {
                var    resultFromExtrnalSharing = await result;
                string _strURL                         = resultFromExtrnalSharing.SiteCollectionURL;
                string _strUserID                      = resultFromExtrnalSharing.SPOExternalUserID;
                bool   _isPermissionGranted            = false;
                bool   _isSiteCollectionSharingEnabled = false;
                bool   _isTenantSharingEnabled         = false;

                try
                {
                    SharePointPrimary obj = new SharePointPrimary(_strURL);

                    List <string> lstSiteCollectionAdmins = new List <string>();
                    lstSiteCollectionAdmins = obj.GetSiteCollectionAdmins();
                    string strSiteCollectionAdmins = string.Empty;

                    foreach (var eachAdmin in lstSiteCollectionAdmins)
                    {
                        strSiteCollectionAdmins += eachAdmin + "; ";
                    }

                    _isTenantSharingEnabled = obj.IsTenantExternalSharingEnabled();
                    if (_isTenantSharingEnabled)
                    {
                        _isSiteCollectionSharingEnabled = obj.IsSiteCollectionExternalSharingEnabled(_strURL);
                        if (_isSiteCollectionSharingEnabled)
                        {
                            _isPermissionGranted = obj.HasAccessGrantedToExternalUser(_strURL, _strUserID);

                            if (_isPermissionGranted)
                            {
                                await context.PostAsync($"Access granted \U00002705 An email is sent to '{_strUserID}' ");

                                //context.Done("External Access granted.");
                                context.Done("Done");
                            }
                            else
                            {
                                await context.PostAsync("Permission could not be granted. Please try again later.");

                                //context.Done("External Access could not be granted.");
                                context.Done("Not Done");
                            }
                        }
                        else
                        {
                            await context.PostAsync($"Access could not be granted as External Sharing is disabled for this Site Collection.");

                            await context.PostAsync($"Please reach out to one of the Site Collection Adminstrators listed below:" +
                                                    "\r\r" + strSiteCollectionAdmins);

                            //context.Done("Access could not be granted. External Sharing is disabled for this Site Collection.");
                            context.Done("Not Done");
                        }
                    }
                    else
                    {
                        await context.PostAsync($"Access could not be granted as External Sharing is disabled at our Tenant level. ");

                        await context.PostAsync($"Please reach out to one of the Site Collection Adminstrators listed below:" +
                                                "\r\r" + strSiteCollectionAdmins);

                        //context.Done("Access could not be granted. External Sharing is disabled at our Tenant level.");
                        context.Done("Not Done");
                    }
                }
                catch (Exception)
                {
                    context.Fail(new Exception("Unable to grant permission to user \U0001F641 . Please try again later."));
                }
            }
            catch (TooManyAttemptsException)
            {
                await context.PostAsync("Sorry \U0001F641 , I am unable to understand you. Let us try again.");
            }
        }
Ejemplo n.º 26
0
        private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <object> result)
        {
            var    activity = await result as Activity;
            string msg      = activity.Text.ToLower().Trim();

            if (msg == "start over" || msg == "exit" || msg == "quit" || msg == "done" || msg == "start again" || msg == "restart" || msg == "leave" || msg == "reset" || msg == "bye" || msg == "goodbye")
            {
                context.Done("end");
            }
            else
            {
                if (isSessionTimedOut(context))
                {
                    context.Fail(new SessionTimedOutException("Your session has timedout or is invalid."));
                }
                else
                {
                    string fhirserver = null;
                    context.PrivateConversationData.TryGetValue <string>("fhirserver", out fhirserver);
                    string token = null;
                    context.PrivateConversationData.TryGetValue <string>("bearertoken", out token);
                    string patid = null;
                    context.PrivateConversationData.TryGetValue <string>("id", out patid);
                    //Initialize FHIR Client
                    FHIRClient client = new FHIRClient(fhirserver, token);
                    //Determine Intent/Entities from LUIS
                    var luisresp = await LUISClient.RequestAsync <LUISResponse>(activity.Text);

                    var intent = luisresp.topScoringIntent;

                    //Nothing over 50% confidence bail
                    if (intent == null)
                    {
                        await context.PostAsync($"Sorry, I didn't understand {activity.Text}...");
                    }

                    if (intent.intent == "FindPractitioner")
                    {
                        if (luisresp.entities == null || luisresp.entities.Count() == 0)
                        {
                            await context.PostAsync($"Sorry, I think you want to find a practioner but I can't determine the location you want");
                        }
                        //Handle Geography
                        var geo = luisresp.entities.FirstOrDefault();
                        //Call FHIR Server
                        string parm   = geo.entity.ToLower().StartsWith("anywhere") ? "" : $"city={geo.entity}";
                        var    bundle = (Hl7.Fhir.Model.Bundle)client.LoadResource("Practitioner", parm);
                        if (bundle.Entry.Count == 0)
                        {
                            await context.PostAsync($"Sorry, I couldn't find providers in {geo.entity}...");
                        }
                        else
                        {
                            StringBuilder sb = new StringBuilder();
                            sb.Append($"Got {bundle.Entry.Count()} practioners in {geo.entity}\n\n");
                            foreach (var entry in bundle.Entry)
                            {
                                Hl7.Fhir.Model.Practitioner p = (Hl7.Fhir.Model.Practitioner)entry.Resource;
                                var address = (p.Address.Count > 0 ? p.Address[0] : null);
                                var tel     = (p.Telecom.Count > 0 ? p.Telecom[0] : null);
                                sb.Append($"{p.Name[0].Text} is accepting new patients.");
                                if (address != null)
                                {
                                    sb.Append($"Located at " + address.LineElement[0] + " " + address.City);
                                }
                                if (tel != null)
                                {
                                    sb.Append($" Phone:" + tel.Value);
                                }
                                sb.Append("\n\n");
                            }
                            await context.PostAsync(sb.ToString());
                        }
                    }
                    else if (intent.intent == "ChartHeartRate")
                    {
                        var entity = luisresp.FindEntityByType("builtin.number");
                        if (entity != null)
                        {
                            var hr = Convert.ToDecimal(new String(entity.entity.Where(Char.IsDigit).ToArray()));
                            Hl7.Fhir.Model.Observation rv = new Hl7.Fhir.Model.Observation();
                            rv.Status   = Hl7.Fhir.Model.ObservationStatus.Final;
                            rv.Category = new List <Hl7.Fhir.Model.CodeableConcept>();
                            Hl7.Fhir.Model.CodeableConcept cc = new Hl7.Fhir.Model.CodeableConcept("http://hl7.org/fhir/observation-category", "vital-signs", "Vital Signs");
                            rv.Category.Add(cc);
                            rv.Code      = new Hl7.Fhir.Model.CodeableConcept("http://loinc.org", "8867-4", "Heart rate");
                            rv.Subject   = new Hl7.Fhir.Model.ResourceReference("patient/" + patid);
                            rv.Effective = Hl7.Fhir.Model.FhirDateTime.Now();
                            rv.Value     = new Hl7.Fhir.Model.Quantity(hr, "beats/minute");
                            var rslt = client.SaveResource(rv);
                            if (rslt)
                            {
                                await context.PostAsync($"Thanks, I recorded your heart rate of {entity.entity} in your medical record");
                            }
                            else
                            {
                                await context.PostAsync($"Sorry I had a problem posting your heartrate...try again later.");
                            }
                        }
                        else
                        {
                            await context.PostAsync($"Sorry, I think you want to record your heartrate vital but I can't understand the value you provided.");
                        }
                    }
                    else if (intent.intent == "ChartWeight")
                    {
                        string entity_weight = null;
                        var    entity        = luisresp.FindEntityByType("weight");
                        if (entity == null)
                        {
                            entity = luisresp.FindEntityByType("builtin.number");
                            if (entity != null)
                            {
                                entity_weight = entity.entity;
                                var wt = luisresp.FindEntityByType("builtin.dimension");
                                if (wt != null)
                                {
                                    if (wt.entity.ToLower().EndsWith("kilograms") || wt.entity.ToLower().EndsWith("kg"))
                                    {
                                        entity_weight = entity_weight + "kg";
                                    }
                                    else
                                    {
                                        entity_weight = entity_weight + "lbs";
                                    }
                                }
                            }
                        }
                        else
                        {
                            entity_weight = entity.entity;
                        }
                        if (entity_weight != null)
                        {
                            var weight = Convert.ToDecimal(new String(entity_weight.Where(Char.IsDigit).ToArray()));
                            //Determine pounds or kg
                            if (entity_weight.ToLower().EndsWith("kg"))
                            {
                                weight = weight * (decimal)2.20462;
                            }
                            Hl7.Fhir.Model.Observation rv = new Hl7.Fhir.Model.Observation();
                            rv.Status   = Hl7.Fhir.Model.ObservationStatus.Final;
                            rv.Category = new List <Hl7.Fhir.Model.CodeableConcept>();
                            Hl7.Fhir.Model.CodeableConcept cc = new Hl7.Fhir.Model.CodeableConcept("http://hl7.org/fhir/observation-category", "vital-signs", "Vital Signs");
                            rv.Category.Add(cc);
                            rv.Code = new Hl7.Fhir.Model.CodeableConcept("http://loinc.org", "29463-7", "Body Weight");
                            rv.Code.Coding.Add(new Hl7.Fhir.Model.Coding("http://snomed.info/sct", "27113001", "Body Weight"));
                            rv.Subject   = new Hl7.Fhir.Model.ResourceReference("patient/" + patid);
                            rv.Effective = Hl7.Fhir.Model.FhirDateTime.Now();
                            rv.Value     = new Hl7.Fhir.Model.Quantity(weight, "lbs");
                            ((Hl7.Fhir.Model.Quantity)rv.Value).Code = "[lb_av]";
                            var rslt = client.SaveResource(rv);
                            if (rslt)
                            {
                                string weightmsg = "";
                                string parm      = $"patient={patid}";
                                var    bundle    = (Hl7.Fhir.Model.Bundle)client.LoadResource("Observation", parm);
                                List <Hl7.Fhir.Model.Observation> weights = new List <Hl7.Fhir.Model.Observation>();
                                foreach (Hl7.Fhir.Model.Bundle.EntryComponent entry in bundle.Entry)
                                {
                                    Hl7.Fhir.Model.Observation o = (Hl7.Fhir.Model.Observation)entry.Resource;
                                    if (FHIRUtils.isCodeMatch(o.Code.Coding, "http://loinc.org", "29463-7"))
                                    {
                                        weights.Add(o);
                                    }
                                }
                                if (weights.Count > 1)
                                {
                                    Hl7.Fhir.Model.Observation[] sorted = weights.OrderBy(o => Convert.ToDateTime(o.Effective.ToString())).ToArray();
                                    decimal prevw = ((Hl7.Fhir.Model.SimpleQuantity)sorted[sorted.Length - 2].Value).Value.Value;
                                    decimal curw  = ((Hl7.Fhir.Model.SimpleQuantity)sorted[sorted.Length - 1].Value).Value.Value;
                                    decimal dif   = prevw - curw;
                                    if (dif < 0)
                                    {
                                        weightmsg = "Looks like you gained around " + Math.Round(Math.Abs(dif), 1) + " lbs.";
                                    }
                                    else if (dif > 0)
                                    {
                                        weightmsg = "Looks like you loss around " + Math.Round(Math.Abs(dif), 1) + " lbs. Keep it up!!";
                                    }
                                    else
                                    {
                                        weightmsg = "Your weight is holding steady";
                                    }
                                }
                                await context.PostAsync($"Thanks, I recorded your weight of {weight} lbs in your medical record\n\n{weightmsg}");
                            }
                            else
                            {
                                await context.PostAsync($"Sorry I had a problem posting your weight...try again later.");
                            }
                        }
                    }
                    else if (intent.intent == "ChartGlucose")
                    {
                        var entity = luisresp.FindEntityByType("builtin.number");
                        if (entity != null)
                        {
                            var glucose = Convert.ToDecimal(new String(entity.entity.Where(Char.IsDigit).ToArray()));
                            var unit    = "mg/dL";
                            Hl7.Fhir.Model.CodeableConcept loinc = new Hl7.Fhir.Model.CodeableConcept("http://loinc.org", "2345-7", "Glucose [Mass/​volume] in Serum or Plasma");
                            //convert mg/DL if mmol/l
                            if (glucose < 20)
                            {
                                glucose = glucose * 18;
                            }
                            Hl7.Fhir.Model.Observation rv = new Hl7.Fhir.Model.Observation();
                            rv.Status   = Hl7.Fhir.Model.ObservationStatus.Final;
                            rv.Category = new List <Hl7.Fhir.Model.CodeableConcept>();
                            Hl7.Fhir.Model.CodeableConcept cc = new Hl7.Fhir.Model.CodeableConcept("http://hl7.org/fhir/observation-category", "laboratory", "Laboratory");
                            rv.Category.Add(cc);
                            rv.Code           = loinc;
                            rv.Subject        = new Hl7.Fhir.Model.ResourceReference("patient/" + patid);
                            rv.Effective      = Hl7.Fhir.Model.FhirDateTime.Now();
                            rv.Issued         = DateTimeOffset.UtcNow;
                            rv.ReferenceRange = new List <Hl7.Fhir.Model.Observation.ReferenceRangeComponent>();
                            Hl7.Fhir.Model.Observation.ReferenceRangeComponent rrc = new Hl7.Fhir.Model.Observation.ReferenceRangeComponent();
                            rrc.High        = new Hl7.Fhir.Model.SimpleQuantity();
                            rrc.High.Unit   = "mg/dL";
                            rrc.High.Code   = rrc.High.Unit;
                            rrc.High.System = "http://unitsofmeasure.org";
                            rrc.High.Value  = 140;
                            rrc.Low         = new Hl7.Fhir.Model.SimpleQuantity();
                            rrc.Low.Unit    = "mg/dL";
                            rrc.Low.Code    = rrc.Low.Unit;
                            rrc.Low.System  = "http://unitsofmeasure.org";
                            rrc.Low.Value   = 70;
                            rv.ReferenceRange.Add(rrc);
                            rv.Value = new Hl7.Fhir.Model.Quantity(glucose, unit);
                            ((Hl7.Fhir.Model.Quantity)rv.Value).Code = unit;
                            var rslt = client.SaveResource(rv);
                            if (rslt)
                            {
                                int     numglucose = 0;
                                string  parm       = $"patient={patid}";
                                var     bundle     = (Hl7.Fhir.Model.Bundle)client.LoadResource("Observation", parm);
                                decimal bga        = 0;
                                foreach (Hl7.Fhir.Model.Bundle.EntryComponent entry in bundle.Entry)
                                {
                                    Hl7.Fhir.Model.Observation o = (Hl7.Fhir.Model.Observation)entry.Resource;
                                    if (FHIRUtils.isCodeMatch(o.Code.Coding, "http://loinc.org", "2345-7"))
                                    {
                                        bga = bga + ((Hl7.Fhir.Model.SimpleQuantity)o.Value).Value.Value;
                                        numglucose++;
                                    }
                                }
                                bga = Math.Round(bga / numglucose, 1);
                                decimal a1c   = ((Convert.ToDecimal(46.7) + bga) / Convert.ToDecimal(28.7));
                                string  bgmsg = $"Your blood glucose is averaging {bga}  mg/dL " + (bga > 140 ? "looks like it's running high" : (bga < 70 ? "looks like it's running low" : ""));
                                bgmsg = bgmsg + "\n\nYour estimated A1C is " + Convert.ToString(Math.Round(a1c, 1));

                                await context.PostAsync($"Thanks, I recorded your blood glucose of {glucose} mg/dL in your medical record\n\n{bgmsg}");
                            }
                            else
                            {
                                await context.PostAsync($"Sorry I had a problem posting your blood glucose...you can try again later.");
                            }
                        }
                        else
                        {
                            await context.PostAsync($"Sorry, I couldnt determine your blood glucose value...try again");
                        }
                    }
                    else if (intent.intent == "DisplayGlucose")
                    {
                        int      numglucose = 0;
                        string   parm       = $"patient={patid}";
                        var      bundle     = (Hl7.Fhir.Model.Bundle)client.LoadResource("Observation", parm);
                        decimal  bga        = 0;
                        decimal  la1c       = 0;
                        decimal  ea1c       = 0;
                        DateTime?dta1c      = null;
                        foreach (Hl7.Fhir.Model.Bundle.EntryComponent entry in bundle.Entry)
                        {
                            Hl7.Fhir.Model.Observation o = (Hl7.Fhir.Model.Observation)entry.Resource;
                            if (FHIRUtils.isCodeMatch(o.Code.Coding, "http://loinc.org", "2345-7"))
                            {
                                bga = bga + ((Hl7.Fhir.Model.SimpleQuantity)o.Value).Value.Value;
                                numglucose++;
                            }
                            else if (FHIRUtils.isCodeMatch(o.Code.Coding, "http://loinc.org", "4548-4"))
                            {
                                la1c  = ((Hl7.Fhir.Model.SimpleQuantity)o.Value).Value.Value;
                                dta1c = Convert.ToDateTime(o.Effective.ToString());
                            }
                        }
                        if (numglucose > 0)
                        {
                            bga  = Math.Round(bga / numglucose, 1);
                            ea1c = ((Convert.ToDecimal(46.7) + bga) / Convert.ToDecimal(28.7));
                        }
                        string a1cmsg = "I don't see any A1C tests on file for you.";
                        string bgmsg  = "I don't see any blood glucose tests on file for you.";
                        if (la1c > 0)
                        {
                            a1cmsg = $"Your last A1C test was on " + String.Format("{0:MM/dd/yyyy}", dta1c.Value) + " the result was " + Convert.ToString(la1c) + "% " + (la1c > 6 ? "thats high" : "");
                        }
                        if (bga > 0)
                        {
                            bgmsg = $"Your blood glucose is averaging {bga}  mg/dL " + (bga > 140 ? "looks like it's running high" : (bga < 70 ? "looks like it's running low" : ""));
                            bgmsg = bgmsg + "\n\nYour current estimated A1C is " + Convert.ToString(Math.Round(ea1c, 1)) + (ea1c < 6 ? " great control!" : (ea1c <= 7 ? " doing good for a diabetic!" : " need to work at lowering!"));
                        }
                        await context.PostAsync($"{a1cmsg}\n\n{bgmsg}");
                    }
                    else if (intent.intent == "DisplayCareplan")
                    {
                        //Call FHIR Server
                        string parm   = $"patient={patid}";
                        var    bundle = (Hl7.Fhir.Model.Bundle)client.LoadResource("CarePlan", parm);
                        if (bundle.Entry.Count == 0)
                        {
                            await context.PostAsync($"Sorry, I couldn't find a plan of care for you in the database...");
                        }
                        else
                        {
                            StringBuilder sb = new StringBuilder();
                            sb.Append("Your current plan of care addresses the following conditions:\n\n");
                            Hl7.Fhir.Model.CarePlan cp = (Hl7.Fhir.Model.CarePlan)bundle.Entry[0].Resource;
                            int x = 1;
                            foreach (var cond in cp.Addresses)
                            {
                                sb.Append(x++ + ". " + cond.Display + "\n\n");
                            }
                            sb.Append("\n\nYou have the following goals:\n\n");
                            x = 1;
                            foreach (var goal in cp.Goal)
                            {
                                sb.Append(x++ + ". " + goal.Display + "\n\n");
                            }
                            sb.Append("\n\nYou should:\n\n");
                            x = 1;
                            foreach (var act in cp.Activity)
                            {
                                if (act.Detail != null)
                                {
                                    sb.Append(x++ + ". " + act.Detail.Description + "\n\n");
                                }
                                else
                                {
                                    if (act.Reference != null && act.Reference.Reference.StartsWith("MedicationRequest"))
                                    {
                                        sb.Append(x++ + ". Take " + act.Reference.Display + " as directed.\n\n");
                                    }
                                }
                            }
                            await context.PostAsync(sb.ToString());
                        }
                    }
                    else
                    {
                        await context.PostAsync($"Sorry, I didn't understand {activity.Text}...");
                    }
                }
                context.Wait(MessageReceivedAsync);
            }
        }
Ejemplo n.º 27
0
        private async Task ModelReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> result)
        {
            var message = await result;

            var found = false;

            if (message.Text != null)
            {
                var model = message.Text.ToLower();
                if (model.Contains("brio amaze") || model.Contains("brioamaze"))
                {
                    found = true;
                    this.user.sellInCar         = "Honda Brio Amaze";
                    this.user.sellInOriginPrice = 577000;
                }
                else if (model.Contains("brio"))
                {
                    found = true;
                    this.user.sellInCar         = "Honda Brio";
                    this.user.sellInOriginPrice = 495000;
                }
                else if (model.Contains("jazz"))
                {
                    found = true;
                    this.user.sellInCar         = "Honda Jazz";
                    this.user.sellInOriginPrice = 670000;
                }
                else if (model.Contains("city"))
                {
                    found = true;
                    this.user.sellInCar         = "Honda City";
                    this.user.sellInOriginPrice = 670000;
                }
                else if (model.Contains("mobilio"))
                {
                    found = true;
                    this.user.sellInCar         = "Honda Mobilio";
                    this.user.sellInOriginPrice = 699999;
                }
                else if (model.Contains("civic hatchback") || model.Contains("civichatchback"))
                {
                    found = true;
                    this.user.sellInCar         = "Honda Civic HATCHBACK";
                    this.user.sellInOriginPrice = 1169000;
                }
                else if (model.Contains("civic"))
                {
                    found = true;
                    this.user.sellInCar         = "Honda Civic";
                    this.user.sellInOriginPrice = 980000;
                }
                else if (model.Contains("hr-v") || model.Contains("hrv"))
                {
                    found = true;
                    this.user.sellInCar         = "Honda HR-V";
                    this.user.sellInOriginPrice = 1050000;
                }
                else if (model.Contains("br-v") || model.Contains("brv"))
                {
                    found = true;
                    this.user.sellInCar         = "Honda BR-V";
                    this.user.sellInOriginPrice = 790000;
                }
                else if (model.Contains("cr-v") || model.Contains("crv"))
                {
                    found = true;
                    this.user.sellInCar         = "Honda CR-V";
                    this.user.sellInOriginPrice = 1549000;
                }
                else if (model.Contains("accord hybrid") || model.Contains("accordhybrid"))
                {
                    found = true;
                    this.user.sellInCar         = "Honda Accord Hybrid";
                    this.user.sellInOriginPrice = 1750000;
                }
                else if (model.Contains("accord"))
                {
                    found = true;
                    this.user.sellInCar         = "Honda Accord";
                    this.user.sellInOriginPrice = 1445000;
                }
            }

            if (found)
            {
                await context.PostAsync($"ระบุปีที่ซื้อรถคันเก่าของ{this.user.genderThai}ด้วยเถิด");

                context.Wait(this.YearReceivedAsync);
            }
            else
            {
                --modelAttempts;
                if (modelAttempts > 0)
                {
                    await context.PostAsync($"ข้าไม่เข้าใจ โปรดระบุรุ่นรถของ{this.user.genderThai}ด้วยเถิดหนา (เช่น Honda Jazz เฉพาะรถของ Honda)");

                    context.Wait(this.ModelReceivedAsync);
                }
                else
                {
                    context.Fail(new TooManyAttemptsException("ข้อความที่ออเจ้าส่งมาไม่ใช่รถของ Honda นะเจ้าคะ"));
                }
            }
        }
Ejemplo n.º 28
0
 public async Task StartAsync(IDialogContext context)
 {
     context.Fail(new NotImplementedException("This is work in progress!!"));
 }
Ejemplo n.º 29
0
        private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> argument)
        {
            var message = await argument;

            if (message.Attachments != null && message.Attachments.Count > 0)
            {
                var attachment = message.Attachments[0];

                if (attachment.ContentType == "image/png" || attachment.ContentType == "image/jpeg")
                {
                    dynamic json = await FaceAPI.GetFaceAPIJson(attachment.ContentUrl);

                    this.user.photoUrl = await AzureBlob.UploadPhoto(attachment.ContentUrl, attachment.ContentType);

                    if (json.Count > 0)
                    {
                        var face = json[0]["faceAttributes"];
                        this.user.gender = face["gender"].ToString();
                        this.user.age    = decimal.Parse(face["age"].ToString());

                        this.user.smile     = decimal.Parse(face["smile"].ToString());
                        this.user.glasses   = face["glasses"].ToString();
                        this.user.anger     = decimal.Parse(face["emotion"]["anger"].ToString());
                        this.user.eyeMakeup = Convert.ToBoolean(face["makeup"]["eyeMakeup"].ToString());
                        this.user.lipMakeup = Convert.ToBoolean(face["makeup"]["lipMakeup"].ToString());

                        this.user.hair = face["hair"].ToString();
                        this.user.bald = decimal.Parse(face["smile"].ToString());
                        var hairColor = face["hair"]["hairColor"];
                        if (hairColor.Count > 0)
                        {
                            this.user.hairColor = hairColor[0]["color"].ToString();
                        }
                        else
                        {
                            this.user.hairColor = "";
                        }
                        this.user.moustache = decimal.Parse(face["facialHair"]["moustache"].ToString());
                        this.user.beard     = decimal.Parse(face["facialHair"]["beard"].ToString());
                        this.user.emotion   = face["emotion"].ToString();

                        if (this.user.gender == "male")
                        {
                            this.user.genderThai = "ท่านหมื่น";
                        }
                        else
                        {
                            this.user.genderThai = "แม่หญิง";
                        }

                        if (this.user.eyeMakeup || this.user.lipMakeup)
                        {
                            this.user.makeupStr = "ชอบการแต่งตัว";
                        }
                        else
                        {
                            this.user.makeupStr = "เป็นคนง่ายๆ สบายๆ";
                        }

                        if (this.user.smile > 0.0M)
                        {
                            this.user.smileStr = "รักความสนุกสนาน";
                        }
                        else
                        {
                            if (this.user.eyeMakeup || this.user.lipMakeup)
                            {
                                this.user.smileStr = "ชอบความเรียบง่าย";
                            }
                            else
                            {
                                this.user.smileStr = "ชอบความโก้หรู";
                            }
                        }

                        if (this.user.anger > 0.7M)
                        {
                            this.user.angerStr = "ชอบความปราดเปรียว";
                        }
                        else
                        {
                            this.user.angerStr = "";
                        }

                        var quiz = $"ข้าเห็นหน้าออเจ้าแล้ว ออเจ้าเป็น{this.user.genderThai} ใช่หรือไม่";
                        PromptDialog.Choice(context, this.OnGenderSelected, yesNoOptions, quiz, "ออเจ้าเลือกไม่ถูกต้อง", 3);
                    }
                    else
                    {
                        --attempts;
                        await context.PostAsync($"ออเจ้าไม่ได้ส่งรูปใบหน้าของออเจ้ามา ส่งรูปหน้าออเจ้ามาให้ข้าด้วยเถิด");

                        context.Wait(MessageReceivedAsync);
                    }
                }
                else
                {
                    --attempts;
                    await context.PostAsync($"ออเจ้าไม่ได้ส่งรูปใบหน้าของออเจ้ามา ส่งรูปหน้าออเจ้ามาให้ข้าด้วยเถิด");

                    context.Wait(MessageReceivedAsync);
                }
            }
            else
            {
                --attempts;
                await context.PostAsync($"ส่งรูปหน้าออเจ้ามาให้ข้าด้วยเถิด");

                context.Wait(MessageReceivedAsync);
            }

            if (attempts <= 0)
            {
                context.Fail(new TooManyAttemptsException("รูปที่ออเจ้าส่งมาไม่ถูกต้อง"));
            }
        }
Ejemplo n.º 30
0
        private async Task MessageReceivedAsync2(IDialogContext context, IAwaitable <IMessageActivity> result)
        {
            var    message = await result;
            string times   = message.Text.Trim();

            if ((message.Text != null) && (times.Length == 5) && (times[0] >= 48 && times[0] <= 50) && (times[1] >= 48 && times[1] <= 57) && (times[3] >= 48 && times[3] <= 50) && (times[4] >= 48 && times[4] <= 57) && times[2] == '-')
            {
                int exactDate1 = 10 * (times[0] - 48) + (times[1] - 48);
                int exactDate2 = 10 * (times[3] - 48) + (times[4] - 48);

                if ((exactDate1 >= 0 && exactDate1 <= 24) && (exactDate2 >= 0 && exactDate2 <= 24))
                {
                    if (exactDate1 > exactDate2)
                    {
                        int i = exactDate1;
                        exactDate1 = exactDate2;
                        exactDate2 = i;
                    }

                    real_time1 = exactDate1;
                    real_time2 = exactDate2;

                    await context.PostAsync(real_time1 + "시부터 " + real_time2 + "시까지를 선택하였습니다. 잠시만 기다려주세요.");

                    // 데이터베이스 입력
                    try
                    {
                        SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
                        builder.DataSource     = "pyeongchang.database.windows.net";
                        builder.UserID         = "hjs0579";
                        builder.Password       = "******";
                        builder.InitialCatalog = "PyeongChangDatabase";

                        using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
                        {
                            Console.WriteLine("\nQuery data example:");
                            Console.WriteLine("=========================================\n");

                            connection.Open();
                            StringBuilder sb = new StringBuilder();
                            sb.Append("SELECT * ");
                            sb.Append("FROM [dbo].[SportsInformation] ");
                            sb.Append("WHERE [Day] = " + real_date + "and [StartTime_H] >= " + real_time1 + "and [EndTime_H] < " + real_time2);
                            String sql = sb.ToString();

                            using (SqlCommand command = new SqlCommand(sql, connection))
                            {
                                using (SqlDataReader reader = command.ExecuteReader())
                                {
                                    while (reader.Read())
                                    {
                                        await context.PostAsync(
                                            "Sports: " + reader.GetString(0) +
                                            "\nDescription: " + reader.GetString(1) +
                                            "\nDate: " + reader.GetString(3) + "." + reader.GetString(4) + "." + reader.GetString(5) +
                                            "\nDay of Week: " + reader.GetString(6) +
                                            "\nStart Time: " + reader.GetString(7) + ":" + reader.GetString(8) +
                                            "\nEnd Time: " + reader.GetString(9) + ":" + reader.GetString(10) +
                                            "\nVenue: " + reader.GetString(11));
                                    }
                                }
                            }
                        }
                    }
                    catch (SqlException e)
                    {
                        Console.WriteLine(e.Message);
                        Console.WriteLine(e.Source);
                        Console.WriteLine(e.StackTrace);
                        Console.WriteLine(e.ToString());
                    }

                    context.Done(times);
                }
                else
                {
                    --attempts;
                    if (attempts > 0)
                    {
                        await context.PostAsync("선택 가능한 시간은 00시부터 24시까지입니다. 원하는 시간 범위를 다시 입력해주세요. 시 단위로만 선택 가능하며 선택 가능한 시간은 00시부터 24시까지입니다. 형식에 맞게 입력해주세요. e.g. 01-23");

                        context.Wait(this.MessageReceivedAsync2);
                    }
                    else
                    {
                        context.Fail(new TooManyAttemptsException("너무 많이 잘못된 메시지를 입력하였습니다."));
                    }
                }
            }
            else
            {
                --attempts;
                if (attempts > 0)
                {
                    await context.PostAsync("이해하지 못하였습니다. 원하는 시간 범위를 다시 입력해주세요. 시 단위로만 선택 가능하며 선택 가능한 시간은 00시부터 24시까지입니다. 형식에 맞게 입력해주세요. e.g. 01-23");

                    context.Wait(this.MessageReceivedAsync2);
                }
                else
                {
                    context.Fail(new TooManyAttemptsException("너무 많이 잘못된 메시지를 입력하였습니다."));
                }
            }
        }