コード例 #1
0
        private static async Task CompleteDialog(IDialogContext context, ComplexWeatherForm state)
        {
            await context.PostAsync("Wait a sec. Thinking...", "en-US");

            var weatherClient = new WeatherClient("88597cb7a556c191905de0f52f23d7d6");
            string message;
            try
            {
                var forecastArray = await weatherClient.Forecast(state.City);
                var forecast = forecastArray?.SingleOrDefault(f => f.When.Date == state.Date?.Date);

                if (forecast != null)
                {
                    if (state.Parameter == ComplexParameterOptions.Humidity) { message = $"The humidity on {forecast.ShortDate} in {forecast.City} is {forecast.Humidity}\r\n"; }
                    else if (state.Parameter == ComplexParameterOptions.Pressure) { message = $"The pressure on {forecast.ShortDate} in {forecast.City} is {forecast.Pressure}\r\n"; }
                    else if (state.Parameter == ComplexParameterOptions.Temperature) { message = $"The temperature on {forecast.ShortDate} in {forecast.City} is {forecast.Temp}\r\n"; }
                    else { message = "Sorry, unknown parameter \"{parameter}\" requested... Try again"; }
                }
                else { message = "Sorry! I was not able to get the forecast."; }
            }
            catch (Exception)
            {
                message = $"Sorry! I was not able to get the forecast.";
            }

            await context.PostAsync(message, "en-US");
            context.Done<object>(null);
        }
コード例 #2
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("너무 많이 잘못된 메시지를 입력하였습니다."));
                }
            }
        }
コード例 #3
0
        public async Task StartAsync(IDialogContext context)
        {
            await context.PostAsync(HelpMessage);

            context.Done(true);
        }
コード例 #4
0
        public override async Task RegisterForEventListingAsync(IDialogContext context, string eventListingId)
        {
            var redirectUrl  = ConfigurationManager.AppSettings["meetupRedirectUrl"];
            var clientId     = ConfigurationManager.AppSettings["meetupClientId"];
            var groupUrlName = ConfigurationManager.AppSettings["meetupGroupUrl"];

            if (string.IsNullOrEmpty(redirectUrl))
            {
                throw new Exception(@"populate appsetting <add key=""meetupRedirectUrl"" value=""""/>");
            }
            if (string.IsNullOrEmpty(clientId))
            {
                throw new Exception(@"populate appsetting <add key=""meetupClientId"" value=""""/>");
            }
            if (string.IsNullOrEmpty(groupUrlName))
            {
                throw new Exception(@"populate appsetting <add key=""meetupGroupUrl"" value=""""/>");
            }

            var userId   = context.Activity.Recipient.Id;
            var existing = TableStorageService.RetrieveByUserId(userId);

            if (existing == null)
            {
                var authMessage = context.MakeMessage();
                authMessage.Attachments.Add(await CardsUtility.CreateAuthCard(clientId, redirectUrl, userId));
                await context.PostAsync(authMessage);

                // TODO wait for auth flow to complete
                var start = DateTime.Now;
                while (existing == null && (DateTime.Now - start).TotalSeconds < 120)
                {
                    Thread.Sleep(5000);
                    existing = TableStorageService.RetrieveByUserId(userId);
                }
                // end TODO

                if (existing != null)
                {
                    await Rsvp(context, existing.AccessToken, groupUrlName, eventListingId);
                }
                else
                {
                    await context.SayAsync("Timed out waiting for Meetup.com authentication to complete. Please try again.");
                }
                context.Done <object>(new object());
            }

            // subtract 1 hour to ensure is an overlap
            else if (existing.ExpiryDateTime <= DateTime.Now.AddMinutes(-60))
            {
                var refreshToken = await OAuthUtility.GetRefreshToken(userId, existing.RefreshToken);

                TableStorageService.InsertOrUpdate(refreshToken);

                await Rsvp(context, existing.AccessToken, groupUrlName, eventListingId);

                context.Done <object>(new object());
            }
            else
            {
                await Rsvp(context, existing.AccessToken, groupUrlName, eventListingId);

                context.Done <object>(new object());
            }
        }
コード例 #5
0
 private async Task Callback(IDialogContext context, IAwaitable <object> result)
 {
     context.Done(true);
 }
コード例 #6
0
ファイル: AutomationDialog.cs プロジェクト: DVDYKC/VAOps
        public async Task ShowRunbookDescriptionAsync(IDialogContext context, LuisResult result)
        {
            EntityRecommendation runbookEntity;
            var accessToken = await context.GetAccessToken(resourceId.Value);

            if (string.IsNullOrEmpty(accessToken))
            {
                return;
            }

            var subscriptionId = context.GetSubscriptionId();

            var availableAutomationAccounts = await new AutomationDomain().ListRunbooksAsync(accessToken, subscriptionId);

            // check if the user specified a runbook name in the command
            if (result.TryFindEntity("Runbook", out runbookEntity))
            {
                // obtain the name specified by the user - text in LUIS result is different
                var runbookName = runbookEntity.GetEntityOriginalText(result.Query);

                // ensure that the runbook exists in at least one of the automation accounts
                var selectedAutomationAccounts = availableAutomationAccounts.Where(x => x.Runbooks.Any(r => r.RunbookName.Equals(runbookName, StringComparison.InvariantCultureIgnoreCase)));

                if (selectedAutomationAccounts == null || !selectedAutomationAccounts.Any())
                {
                    await context.PostAsync($"The '{runbookName}' runbook was not found in any of your automation accounts.");

                    context.Done <string>(null);
                    return;
                }

                if (selectedAutomationAccounts.Count() == 1)
                {
                    var automationAccount = selectedAutomationAccounts.Single();
                    var runbook           = automationAccount.Runbooks.Single(r => r.RunbookName.Equals(runbookName, StringComparison.InvariantCultureIgnoreCase));
                    var description       = await new AutomationDomain().GetAutomationRunbookDescriptionAsync(accessToken, subscriptionId, automationAccount.ResourceGroup, automationAccount.AutomationAccountName, runbook.RunbookName) ?? "No description";
                    await context.PostAsync(description);

                    context.Done <string>(null);
                }
                else
                {
                    var message = $"I found the runbook '{runbookName}' in multiple automation accounts. Showing the description of all of them:";

                    foreach (var automationAccount in selectedAutomationAccounts)
                    {
                        message += $"\n\r {automationAccount.AutomationAccountName}";
                        foreach (var runbook in automationAccount.Runbooks)
                        {
                            if (runbook.RunbookName.Equals(runbookName, StringComparison.InvariantCultureIgnoreCase))
                            {
                                var description = await new AutomationDomain().GetAutomationRunbookDescriptionAsync(accessToken, subscriptionId, automationAccount.ResourceGroup, automationAccount.AutomationAccountName, runbook.RunbookName) ?? "No description";

                                message += $"\n\r• {description}";
                            }
                        }
                    }

                    await context.PostAsync(message);

                    context.Done <string>(null);
                }
            }
            else
            {
                await context.PostAsync($"No runbook was specified. Please try again specifying a runbook name.");

                context.Done <string>(null);
            }
        }
コード例 #7
0
ファイル: AutomationDialog.cs プロジェクト: DVDYKC/VAOps
        public async Task StartRunbookAsync(IDialogContext context, LuisResult result)
        {
            EntityRecommendation runbookEntity;
            var accessToken = await context.GetAccessToken(resourceId.Value);

            if (string.IsNullOrEmpty(accessToken))
            {
                return;
            }

            var subscriptionId = context.GetSubscriptionId();

            var availableAutomationAccounts = await new AutomationDomain().ListRunbooksAsync(accessToken, subscriptionId);

            // check if the user specified a runbook name in the command
            if (result.TryFindEntity("Runbook", out runbookEntity))
            {
                // obtain the name specified by the user - text in LUIS result is different
                var runbookName = runbookEntity.GetEntityOriginalText(result.Query);

                EntityRecommendation automationAccountEntity;

                if (result.TryFindEntity("AutomationAccount", out automationAccountEntity))
                {
                    // obtain the name specified by the user - text in LUIS result is different
                    var automationAccountName = automationAccountEntity.GetEntityOriginalText(result.Query);

                    var selectedAutomationAccount = availableAutomationAccounts.SingleOrDefault(x => x.AutomationAccountName.Equals(automationAccountName, StringComparison.InvariantCultureIgnoreCase));

                    if (selectedAutomationAccount == null)
                    {
                        await context.PostAsync($"The '{automationAccountName}' automation account was not found in the current subscription");

                        context.Done <string>(null);
                        return;
                    }

                    var runbook = selectedAutomationAccount.Runbooks.SingleOrDefault(x => x.RunbookName.Equals(runbookName, StringComparison.InvariantCultureIgnoreCase));

                    // ensure that the runbook exists in the specified automation account
                    if (runbook == null)
                    {
                        await context.PostAsync($"The '{runbookName}' runbook was not found in the '{automationAccountName}' automation account.");

                        context.Done <string>(null);
                        return;
                    }

                    if (!runbook.RunbookState.Equals("Published", StringComparison.InvariantCultureIgnoreCase))
                    {
                        await context.PostAsync($"The '{runbookName}' runbook that you are trying to run is not published (State: {runbook.RunbookState}). Please go the Azure Portal and publish the runbook.");

                        context.Done <string>(null);
                        return;
                    }

                    runbookEntity.Entity = runbookName;
                    runbookEntity.Type   = "RunbookName";

                    automationAccountEntity.Entity = selectedAutomationAccount.AutomationAccountName;
                    automationAccountEntity.Type   = "AutomationAccountName";
                }
                else
                {
                    // ensure that the runbook exists in at least one of the automation accounts
                    var selectedAutomationAccounts = availableAutomationAccounts.Where(x => x.Runbooks.Any(r => r.RunbookName.Equals(runbookName, StringComparison.InvariantCultureIgnoreCase)));

                    if (selectedAutomationAccounts == null || !selectedAutomationAccounts.Any())
                    {
                        await context.PostAsync($"The '{runbookName}' runbook was not found in any of your automation accounts.");

                        context.Done <string>(null);
                        return;
                    }

                    var runbooks = selectedAutomationAccounts.SelectMany(x => x.Runbooks.Where(r => r.RunbookName.Equals(runbookName, StringComparison.InvariantCultureIgnoreCase) &&
                                                                                               r.RunbookState.Equals("Published", StringComparison.InvariantCultureIgnoreCase)));

                    if (runbooks == null || !runbooks.Any())
                    {
                        await context.PostAsync($"The '{runbookName}' runbook that you are trying to run is not Published. Please go the Azure Portal and publish the runbook.");

                        context.Done <string>(null);
                        return;
                    }

                    runbookEntity.Entity = runbookName;
                    runbookEntity.Type   = "RunbookName";

                    // todo: handle runbooks with same name in different automation accounts
                    availableAutomationAccounts = selectedAutomationAccounts.ToList();
                }
            }

            if (availableAutomationAccounts.Any())
            {
                var formState = new RunbookFormState(availableAutomationAccounts);

                if (availableAutomationAccounts.Count() == 1)
                {
                    formState.AutomationAccountName = availableAutomationAccounts.Single().AutomationAccountName;
                }

                var form = new FormDialog <RunbookFormState>(
                    formState,
                    AutomationForms.BuildRunbookForm,
                    FormOptions.PromptInStart,
                    result.Entities);
                context.Call(form, this.StartRunbookParametersAsync);
            }
            else
            {
                await context.PostAsync($"No automations accounts were found in the current subscription. Please create an Azure automation account or switch to a subscription which has an automation account in it.");

                context.Done <string>(null);
            }
        }
コード例 #8
0
        public async Task StartAsync(IDialogContext context)
        {
            await context.PostAsync("Its 1200rs");

            context.Done(true);
        }
コード例 #9
0
 private async Task ResumeAfterWelcomeDone(IDialogContext context, IAwaitable <object> result)
 {
     context.Done <object>(null);
 }
コード例 #10
0
 private async Task AfterHelloCompleted(IDialogContext context, IAwaitable <object> result)
 {
     context.Done <object>(null);
 }
コード例 #11
0
        public async Task StartAsync(IDialogContext context)
        {
            var reply = context.MakeMessage();
            List <AdaptiveChoice> choice = new List <AdaptiveChoice>();

            choice.Add(new AdaptiveChoice()
            {
                Title = "--Select option--", Value = "--Select option--"
            });
            var query = @"query  {
                    viewer{
                        name
                      repositories(first: 100)
                      {
                         nodes
                        {
                         name
                        }
                      }
                    }
                }";

            var           client = new GraphQLClient();
            string        data   = client.Query(query, null);
            AllRepository obj    = Newtonsoft.Json.JsonConvert.DeserializeObject <AllRepository>(data);

            foreach (Node1 rep in obj.data.viewer.repositories.nodes)
            {
                choice.Add(new AdaptiveChoice()
                {
                    Title = rep.name, Value = rep.name
                });
            }
            AdaptiveCard card = new AdaptiveCard()
            {
                Body = new List <AdaptiveElement>()
                {
                    new AdaptiveTextBlock()
                    {
                        Text = "Search Issue", Weight = AdaptiveTextWeight.Bolder, Size = AdaptiveTextSize.Large, Wrap = true, HorizontalAlignment = AdaptiveHorizontalAlignment.Center
                    },
                    new AdaptiveTextBlock()
                    {
                        Text = "Select Repository"
                    },
                    new AdaptiveChoiceSetInput()
                    {
                        Id = "Repository", Style = AdaptiveChoiceInputStyle.Compact, Choices = choice
                    },
                    new AdaptiveTextBlock()
                    {
                        Text = "Select Issue State"
                    },
                    new AdaptiveChoiceSetInput()
                    {
                        Id      = "State", Value = "--ALL--", IsMultiSelect = false, Style = AdaptiveChoiceInputStyle.Compact,
                        Choices = new List <AdaptiveChoice>()
                        {
                            new AdaptiveChoice()
                            {
                                Title = "--ALL--", Value = "--ALL--"
                            },
                            new AdaptiveChoice()
                            {
                                Title = "OPEN",
                                Value = "OPEN"
                            },
                            new AdaptiveChoice()
                            {
                                Title = "CLOSED",
                                Value = "CLOSED"
                            }
                        }
                    }
                },
                Actions = new List <AdaptiveAction>()
                {
                    new AdaptiveSubmitAction()
                    {
                        Title    = "Submit",
                        Id       = "IssueDetail",
                        DataJson = @"{""Action"":""GetIssueDetail""}"
                    }
                }
            };

            Microsoft.Bot.Connector.Attachment attachment = new Microsoft.Bot.Connector.Attachment()
            {
                ContentType = AdaptiveCard.ContentType,
                Content     = card,
                //  Name = "ABCD"
            };

            reply.Attachments.Add(attachment);
            await context.PostAsync(reply);

            context.Done <object>(new object());
        }
コード例 #12
0
            protected virtual async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> item)
            {
                var nextPromptIdx = 0;

                var validationResults = default(ICollection <ValidationResult>);

                this.luisAction.IsValid(out validationResults);

                if (item != null)
                {
                    var message = await item;

                    var paramName  = validationResults.First().MemberNames.First();
                    var paramValue = message.Text;

                    var result = await LuisActionResolver.QueryValueFromLuisAsync(this.luisService, this.luisAction, paramName, paramValue, context.CancellationToken);

                    if (result.Succeed)
                    {
                        nextPromptIdx++;
                    }
                    else if (!string.IsNullOrWhiteSpace(result.NewIntent) && result.NewAction != null)
                    {
                        var currentActionDefinition = LuisActionResolver.GetActionDefinition(this.luisAction);

                        var isContextual = false;
                        if (LuisActionResolver.IsValidContextualAction(result.NewAction, this.luisAction, out isContextual))
                        {
                            var executionContextChain = new List <ActionExecutionContext> {
                                new ActionExecutionContext(result.NewIntent, result.NewAction)
                            };

                            var childDialog = new LuisActionMissingEntitiesDialog(this.luisService, executionContextChain);

                            context.Call(childDialog, this.AfterContextualActionFinished);

                            return;
                        }
                        else if (isContextual & !LuisActionResolver.IsContextualAction(this.luisAction))
                        {
                            var newActionDefinition = LuisActionResolver.GetActionDefinition(result.NewAction);

                            await context.PostAsync($"Cannot execute action '{newActionDefinition.FriendlyName}' in the context of '{currentActionDefinition.FriendlyName}' - continuing with current action");
                        }
                        else if (!this.luisAction.GetType().Equals(result.NewAction.GetType()))
                        {
                            var newActionDefinition = LuisActionResolver.GetActionDefinition(result.NewAction);

                            var valid = LuisActionResolver.UpdateIfValidContextualAction(result.NewAction, this.luisAction, out isContextual);
                            if (!valid && isContextual)
                            {
                                await context.PostAsync($"Cannot switch to action '{newActionDefinition.FriendlyName}' from '{currentActionDefinition.FriendlyName}' due to invalid context - continuing with current action");
                            }
                            else if (currentActionDefinition.ConfirmOnSwitchingContext)
                            {
                                // serialize overrun info
                                this.overrunData = result;

                                PromptDialog.Confirm(
                                    context,
                                    this.AfterOverrunCurrentActionSelected,
                                    $"Do you want to discard the current action '{currentActionDefinition.FriendlyName}' and start executing '{newActionDefinition.FriendlyName}' action?");

                                return;
                            }
                            else
                            {
                                this.intentName = result.NewIntent;
                                this.luisAction = result.NewAction;

                                this.luisAction.IsValid(out validationResults);
                            }
                        }
                    }
                }

                if (validationResults.Count > nextPromptIdx)
                {
                    await context.PostAsync(validationResults.ElementAt(nextPromptIdx).ErrorMessage);

                    context.Wait(this.MessageReceivedAsync);
                }
                else
                {
                    context.Done(new ActionExecutionContext(this.intentName, this.luisAction));
                }
            }
コード例 #13
0
ファイル: HelpDialog.cs プロジェクト: SorraTheOrc/cynosure
        public async Task StartAsync(IDialogContext context)
        {
            await DisplayHelpCard(context);

            context.Done <object>(null);
        }
コード例 #14
0
        public async Task NoIntent(IDialogContext context, LuisResult result)
        {
            LogHelper.LogLuisResult(result, context.Activity, typeof(VehicleReworkedDialog).Name);

            context.Done(false);
        }
コード例 #15
0
        private async Task ResumeAfterFarmingServicesDialog(IDialogContext context, IAwaitable <object> result)
        {
            //await context.PostAsync("Thank you. We're all done. What else can I do for you?");

            context.Done <object>(null);
        }
コード例 #16
0
 private async Task ResumeWelcome(IDialogContext context, IAwaitable <object> result)
 {
     context.Done(true);
 }
コード例 #17
0
        private async Task SelectDialog(IDialogContext context, IAwaitable <object> result)
        {
            var selectedMenu = await result;

            context.Done(selectedMenu);
        }
コード例 #18
0
        private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> argument)
        {
            var msg = await(argument);

            if (msg.Value != null)
            {
                dynamic value      = msg.Value;
                string  submittype = value.Type.ToString();
                switch (submittype)
                {
                case "submitchoice":
                    var reply = context.MakeMessage();
                    reply.Text = "You have selected " + value.undefined.ToString();
                    await context.PostAsync(reply);

                    context.Done("Selected");
                    return;
                }
            }
            if (msg.Text.StartsWith("token:"))
            {
                RestClient client = new RestClient(Constants.ApiUrl);

                string status = string.Empty;
                var    token  = msg.Text.Remove(0, "token:".Length);
                context.PrivateConversationData.SetValue(AuthTokenKey, token);

                var Usermail = await UserInfo(token);

                if (!string.IsNullOrWhiteSpace(Usermail))
                {
                    UserEmail = Usermail;
                    var request = new RestRequest("authorization", Method.GET);
                    request.AddHeader("email", Usermail);

                    try
                    {
                        var response = client.Execute(request);
                        if (response.StatusCode == HttpStatusCode.OK)
                        {
                            status = response.Content;
                            if (status == "true")
                            {
                                await context.PostAsync("Your are logged in.");
                            }
                            else
                            {
                                await context.PostAsync("You are not authorized user. Logged out! Try with valid credentials");

                                context.PrivateConversationData.RemoveValue(AuthTokenKey);
                                //await context.PostAsync("Your are logged out! Try with valid credentials");
                                context.Wait(MessageReceived);
                            }
                        }
                    }
                    catch (Exception error)
                    {
                    }
                }
                context.Done(token);
            }
            else
            {
                await context.PostAsync("Please do login before move forward!");

                //await LogIn(context);
            }
        }
コード例 #19
0
        private async Task ResumeAfterOrderFormDialog(IDialogContext context, IAwaitable <LuggageQuery> result)
        {
            try
            {
                var hasil = await result;
                if (hasil.Results != null)
                {
                    Activity replyToConversation = context.MakeMessage() as Activity; //message.CreateReply("Should go to conversation, in list format");
                    replyToConversation.Attachments = new List <Attachment>();


                    foreach (var item in hasil.Results)
                    {
                        AdaptiveCard card = new AdaptiveCard();

                        // Specify speech for the card.
                        card.Speak = $"<s>Your luggage is at GATE {item.AGATE} in Terminal {item.TERMINAL}, your air line is {item.LONG_NAME} FROM {item.LONG_NAME1} ARRIVED AT {Convert.ToDateTime(item.STA_TIME_STAMP).ToString("dd MMMM yyyy HH:mm")}</s>";

                        // Add text to the card.
                        card.Body.Add(new TextBlock()
                        {
                            Text   = "LUGGAGE INFO",
                            Size   = TextSize.Large,
                            Weight = TextWeight.Bolder
                        });

                        // Add text to the card.
                        card.Body.Add(new TextBlock()
                        {
                            Text = $"AIRLINE : {item.LONG_NAME} - {item.FLIGHT_NUM} "
                        });

                        // Add text to the card.
                        card.Body.Add(new TextBlock()
                        {
                            Text = $"TERMINAL : {item.TERMINAL} "
                        });
                        // Add text to the card.
                        card.Body.Add(new TextBlock()
                        {
                            Text = $"A GATE : {item.AGATE} "
                        });
                        // Add text to the card.
                        card.Body.Add(new TextBlock()
                        {
                            Text = $"ETA : {item.ETA_TIME_STAMP} "
                        });
                        // Add text to the card.
                        card.Body.Add(new TextBlock()
                        {
                            Text = $"ACTUAL CLAIM : {item.ACTUAL_CLAIM} "
                        });
                        card.Body.Add(new TextBlock()
                        {
                            Text = $"STA : {item.STA} "
                        });


                        /*
                         * card.Actions.Add(new HttpAction()
                         * {
                         *  Url = "http://foo.com",
                         *  Title = "Snooze"
                         * });
                         */
                        // Create the attachment.
                        Attachment attachment = new Attachment()
                        {
                            ContentType = AdaptiveCard.ContentType,
                            Content     = card
                        };
                        replyToConversation.Attachments.Add(attachment);
                    }
                    await context.PostAsync(replyToConversation);
                }
                else
                {
                    await context.PostAsync("No result..");
                }
            }
            catch (FormCanceledException ex)
            {
                string reply;

                if (ex.InnerException == null)
                {
                    reply = MESSAGESINFO.CANCEL_DIALOG;
                }
                else
                {
                    reply = $"{MESSAGESINFO.ERROR_INFO} Detail: {ex.InnerException.Message}";
                }

                await context.PostAsync(reply);
            }
            finally
            {
                context.Done <object>(null);
            }
        }
コード例 #20
0
ファイル: AutomationDialog.cs プロジェクト: DVDYKC/VAOps
 public async Task None(IDialogContext context, LuisResult result)
 {
     context.Done(result.Query);
 }
コード例 #21
0
ファイル: ChoiceDialog.cs プロジェクト: virus2304/ModernAI
        private async Task ProcessResult(IDialogContext context, IAwaitable <object> result)
        {
            var res = await result;

            context.Done((string)res);
        }
コード例 #22
0
ファイル: AutomationDialog.cs プロジェクト: DVDYKC/VAOps
        private async Task RunbookFormComplete(IDialogContext context, RunbookFormState runbookFormState)
        {
            try
            {
                var accessToken = await context.GetAccessToken(resourceId.Value);

                if (string.IsNullOrEmpty(accessToken))
                {
                    return;
                }

                var runbookJob = await new AutomationDomain().StartRunbookAsync(
                    accessToken,
                    runbookFormState.SelectedAutomationAccount.SubscriptionId,
                    runbookFormState.SelectedAutomationAccount.ResourceGroup,
                    runbookFormState.SelectedAutomationAccount.AutomationAccountName,
                    runbookFormState.RunbookName,
                    runbookFormState.RunbookParameters.Where(param => !string.IsNullOrWhiteSpace(param.ParameterValue))
                    .ToDictionary(param => param.ParameterName, param => param.ParameterValue));

                IList <RunbookJob> automationJobs = context.GetAutomationJobs(runbookFormState.SelectedAutomationAccount.SubscriptionId);
                if (automationJobs == null)
                {
                    runbookJob.FriendlyJobId = AutomationJobsHelper.NextFriendlyJobId(automationJobs);
                    automationJobs           = new List <RunbookJob> {
                        runbookJob
                    };
                }
                else
                {
                    runbookJob.FriendlyJobId = AutomationJobsHelper.NextFriendlyJobId(automationJobs);
                    automationJobs.Add(runbookJob);
                }

                context.StoreAutomationJobs(runbookFormState.SelectedAutomationAccount.SubscriptionId, automationJobs);

                await context.PostAsync($"Created Job '{runbookJob.JobId}' for the '{runbookFormState.RunbookName}' runbook in '{runbookFormState.AutomationAccountName}' automation account. You'll receive a message when it is completed.");

                var notCompletedStatusList = new List <string> {
                    "Stopped", "Suspended", "Failed"
                };
                var completedStatusList = new List <string> {
                    "Completed"
                };
                var notifyStatusList = new List <string> {
                    "Running"
                };
                notifyStatusList.AddRange(completedStatusList);
                notifyStatusList.AddRange(notCompletedStatusList);

                accessToken = await context.GetAccessToken(resourceId.Value);

                if (string.IsNullOrEmpty(accessToken))
                {
                    return;
                }

#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                CheckLongRunningOperationStatus(
                    context,
                    runbookJob,
                    accessToken,
                    new AutomationDomain().GetAutomationJobAsync,
                    rj => rj.EndDateTime.HasValue,
                    (previous, last, job) =>
                {
                    if (!string.Equals(previous?.Status, last?.Status) && notifyStatusList.Contains(last.Status))
                    {
                        if (notCompletedStatusList.Contains(last.Status))
                        {
                            return($"The runbook '{job.RunbookName}' (job '{job.JobId}') did not complete with status '{last.Status}'. Please go to the Azure Portal for more detailed information on why.");
                        }
                        else if (completedStatusList.Contains(last.Status))
                        {
                            return($"Runbook '{job.RunbookName}' is currently in '{last.Status}' status. Type **show {job.FriendlyJobId} output** to see the output.");
                        }
                        else
                        {
                            return($"Runbook '{job.RunbookName}' job '{job.JobId}' is currently in '{last.Status}' status.");
                        }
                    }

                    return(null);
                });
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
            }
            catch (Exception e)
            {
                await context.PostAsync($"Oops! Something went wrong :(. Technical Details: {e.InnerException.Message}");
            }

            context.Done <string>(null);
        }
コード例 #23
0
        public virtual async Task ChildDialogComplete(IDialogContext context, IAwaitable <object> response)
        {
            await context.PostAsync("Muito obrigado pela atenção!");

            context.Done(this);
        }
コード例 #24
0
        private async Task ResumeAfterHotelsFormDialog(IDialogContext context, IAwaitable <SoftwareQuery> result)
        {
            try
            {
                var searchQuery = await result;

                var hotels = await this.GetHotelsAsync(searchQuery);

                await context.PostAsync($"I found in total {hotels.Count()} hotels for your dates:");

                var resultMessage = context.MakeMessage();
                resultMessage.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                resultMessage.Attachments      = new List <Attachment>();

                foreach (var hotel in hotels)
                {
                    HeroCard heroCard = new HeroCard()
                    {
                        Title    = hotel.Name,
                        Subtitle = $"{hotel.Rating} starts. {hotel.NumberOfReviews} reviews. From ${hotel.PriceStarting} per night.",
                        Images   = new List <CardImage>()
                        {
                            new CardImage()
                            {
                                Url = hotel.Image
                            }
                        },
                        Buttons = new List <CardAction>()
                        {
                            new CardAction()
                            {
                                Title = "More details",
                                Type  = ActionTypes.OpenUrl,
                                Value = $"https://www.bing.com/search?q=hotels+in+" + HttpUtility.UrlEncode(hotel.Location)
                            }
                        }
                    };

                    resultMessage.Attachments.Add(heroCard.ToAttachment());
                }

                await context.PostAsync(resultMessage);
            }
            catch (FormCanceledException ex)
            {
                string reply;

                if (ex.InnerException == null)
                {
                    reply = "You have canceled the operation. Quitting from the HotelsDialog";
                }
                else
                {
                    reply = $"Oops! Something went wrong :( Technical Details: {ex.InnerException.Message}";
                }

                await context.PostAsync(reply);
            }
            finally
            {
                context.Done <object>(null);
            }
        }
コード例 #25
0
        public async Task ResumeAfterDialogFlow(IDialogContext context, IAwaitable <object> result)
        {
            await context.PostAsync(Strings.DialogFlowStep3);

            context.Done <object>(null);
        }
コード例 #26
0
 private async Task FormCompleteCallback(IDialogContext context, IAwaitable <object> input)
 {
     context.Done <object>(null);
 }
コード例 #27
0
        public async Task EndDialog(IDialogContext context, IAwaitable <object> result)
        {
            await context.PostAsync(Strings.EndDialogTitleMsg);

            context.Done <object>(null);
        }
コード例 #28
0
 private Task AfterBuildInfoCheckWasExecuted(IDialogContext context, IAwaitable <object> result)
 {
     context.Done((object)null);
     return(Task.CompletedTask);
 }
コード例 #29
0
        public async Task EndFetchRosterDialog(IDialogContext context, IAwaitable <object> result)
        {
            await context.PostAsync(Strings.ThanksRosterTitleMsg);

            context.Done <object>(null);
        }
コード例 #30
0
 private async Task CallbackCongratulation(IDialogContext context, IAwaitable <object> result)
 {
     context.Done(this);
 }
コード例 #31
0
        private async Task Halfdays(IDialogContext context, IAwaitable <object> result)
        {
            try
            {
                var activity = await result as Activity;
                year = activity.Text;
                // StateClient stateClient = activity.GetStateClient();
                // BotData userData = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);
                {
                    var token = "ok";


                    if (token == null)
                    {
                        await context.PostAsync("Need to Login to access data");

                        // context.Call(new UserLogin(), ResumeAfteNullToken);
                        await context.PostAsync("Please Type **'Hello'** to Login ");

                        context.Done(true);
                    }
                    if (token != null)
                    {
                        // StateClient empCode1 = activity.GetStateClient();
                        //  BotData empCodeu = await empCode1.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);
                        //  var ob = JObject.Parse(empCodeu.Data.ToString());
                        //  var empID = (int)obj["empID"];
                        var empID = context.UserData.GetValue <int>("empID");
                        var Dimattendancemonthly        = new DimattendancemonthlyClient();
                        var DimattendancemonthlyDetails = await Dimattendancemonthly.DimattendancemonthlyDetails(token, empID, month, year);

                        if (DimattendancemonthlyDetails != null && DimattendancemonthlyDetails.ResponseJSON != null &&
                            DimattendancemonthlyDetails.ResponseJSON.PayrollMonth != null)
                        {
                            await context.PostAsync($"Your half days in payroll month {DimattendancemonthlyDetails.ResponseJSON.PayrollMonth}" +
                                                    $" are {DimattendancemonthlyDetails.ResponseJSON.HalfDay} ");

                            //context.Call(new ResumeAfter(), this.ResumeAfterTaskDialog);
                            context.Done(true);
                        }
                        else
                        {
                            await context.PostAsync("Data not found ");

                            context.Done(true);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string filePath = AppDomain.CurrentDomain.BaseDirectory;
                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                sb.Append("InnerException : " + ex.InnerException);
                sb.Append("Halfdays");
                sb.Append(Environment.NewLine);
                sb.Append("Message : " + ex.Message);
                sb.Append(Environment.NewLine);
                System.IO.File.AppendAllText(System.IO.Path.Combine(filePath, "Exception_log.txt"), sb.ToString());
                sb.Clear();
                await context.PostAsync("Data not found");

                context.Done(true);
            }
        }