Exemple #1
0
        public async Task CreateResourceAsync(IDialogContext context)//, LuisResult result)
        {
            var accessToken = await context.GetAccessToken(resourceId.Value);

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

            var subscriptionId = context.GetSubscriptionId();

            //TODO - Take USer input for below parameters
            var groupName         = "hackathonDemo";
            var storageName       = "hacky2016";
            var deploymentName    = "MyVmDeployment";
            var templateContainer = "templates";
            var templateJson      = "azuredeploy.json";
            var parametersJSon    = "azuredeploy.parameters.json";

            await new ResourceGroupDomain().CreateTemplateDeploymentAsync(accessToken, groupName, storageName, deploymentName, subscriptionId, templateContainer, templateJson, parametersJSon);

            await context.PostAsync($"Your VM deployment is initiated. Will let you know once deployment is completed. What's next?");

            context.Done(true);
            //(this.MessageReceived);
        }
Exemple #2
0
        public async Task ListVmsAsync(IDialogContext context, LuisResult result)
        {
            var accessToken = await context.GetAccessToken(resourceId.Value);

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

            var subscriptionId = context.GetSubscriptionId();

            var virtualMachines = (await new VMDomain().ListVirtualMachinesAsync(accessToken, subscriptionId)).ToList();

            if (virtualMachines.Any())
            {
                var virtualMachinesText = virtualMachines.Aggregate(
                    string.Empty,
                    (current, next) =>
                {
                    return(current += $"\n\r• {next}");
                });

                await context.PostAsync($"Available VMs are:\r\n {virtualMachinesText}");
            }
            else
            {
                await context.PostAsync("No virtual machines were found in the current subscription.");
            }

            context.Done <string>(null);
        }
        public async Task ListAutomationAccountsAsync(IDialogContext context, LuisResult result)
        {
            var accessToken = await context.GetAccessToken(resourceId.Value);

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

            var subscriptionId = context.GetSubscriptionId();

            var automationAccounts = await new AutomationDomain().ListAutomationAccountsAsync(accessToken, subscriptionId);

            if (automationAccounts.Any())
            {
                var automationAccountsText = automationAccounts.Aggregate(
                    string.Empty,
                    (current, next) =>
                {
                    return(current += $"\n\r• {next.AutomationAccountName}");
                });

                await context.PostAsync($"Available automations accounts are:\r\n {automationAccountsText}");
            }
            else
            {
                await context.PostAsync("No automations accounts were found in the current subscription.");
            }

            context.Done <string>(null);
        }
        public async Task ListRunbooksAsync(IDialogContext context, LuisResult result)
        {
            var accessToken = await context.GetAccessToken(resourceId.Value);

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

            var subscriptionId = context.GetSubscriptionId();

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

            if (automationAccounts.Any())
            {
                var automationAccountsWithRunbooks = automationAccounts.Where(x => x.Runbooks.Any());

                if (automationAccountsWithRunbooks.Any())
                {
                    var messageText = "Available runbooks are:";

                    var singleAutomationAccount = automationAccountsWithRunbooks.Count() == 1;

                    if (singleAutomationAccount)
                    {
                        messageText = $"Listing all runbooks from {automationAccountsWithRunbooks.Single().AutomationAccountName}";
                    }

                    var runbooksText = automationAccountsWithRunbooks.Aggregate(
                        string.Empty,
                        (current, next) =>
                    {
                        var innerRunbooksText = next.Runbooks.Aggregate(
                            string.Empty,
                            (currentRunbooks, nextRunbook) =>
                        {
                            return(currentRunbooks += $"\n\r• {nextRunbook}");
                        });

                        return(current += singleAutomationAccount ? innerRunbooksText : $"\n\r {next.AutomationAccountName}" + innerRunbooksText);
                    });

                    var showDescriptionText = "Type **show runbook <name> description** to get details on any runbook.";
                    await context.PostAsync($"{messageText}:\r\n {runbooksText} \r\n\r\n {showDescriptionText}");
                }
                else
                {
                    await context.PostAsync($"The automation accounts found in the current subscription doesn't have runbooks.");
                }
            }
            else
            {
                await context.PostAsync("No runbooks listed since no automations accounts were found in the current subscription.");
            }

            context.Done <string>(null);
        }
        public async Task ShowJobOutputAsync(IDialogContext context, LuisResult result)
        {
            EntityRecommendation jobEntity;

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

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

            var subscriptionId = context.GetSubscriptionId();

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

                IList <RunbookJob> automationJobs = context.GetAutomationJobs(subscriptionId);
                if (automationJobs != null)
                {
                    var selectedJob = automationJobs.SingleOrDefault(x => !string.IsNullOrWhiteSpace(x.FriendlyJobId) &&
                                                                     x.FriendlyJobId.Equals(friendlyJobId, StringComparison.InvariantCultureIgnoreCase));

                    if (selectedJob == null)
                    {
                        await context.PostAsync($"The job with id '{friendlyJobId}' was not found.");

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

                    var jobOutput = await new AutomationDomain().GetAutomationJobOutputAsync(accessToken, subscriptionId, selectedJob.ResourceGroupName, selectedJob.AutomationAccountName, selectedJob.JobId);

                    var outputMessage = string.IsNullOrWhiteSpace(jobOutput) ? $"No output for job '{friendlyJobId}'" : jobOutput;

                    await context.PostAsync(outputMessage);
                }
                else
                {
                    await context.PostAsync($"The job with id '{friendlyJobId}' was not found.");
                }
            }
            else
            {
                await context.PostAsync("No runbook job id was specified. Try 'show <jobId> output'.");
            }

            context.Done <string>(null);
        }
        public async Task GetCurrentSubscriptionAsync(IDialogContext context, LuisResult result)
        {
            var accessToken = await context.GetAccessToken(resourceId.Value);

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

            var subscriptionId = context.GetSubscriptionId();

            var currentSubscription = await Domain.Subscription.GetSubscription(accessToken, subscriptionId);

            await context.PostAsync($"Your current subscription is '{currentSubscription.DisplayName}'.");

            context.Wait(MessageReceived);
        }
        protected override async Task MessageReceived(IDialogContext context, IAwaitable <IMessageActivity> item)
        {
            var message = await item;

            //No way to get the message in the LuisIntent methods so saving it here
            userToBot = message.Text.ToLowerInvariant();

            if (!serviceUrlSet)
            {
                context.PrivateConversationData.SetValue("ServiceUrl", message.ServiceUrl);
                serviceUrlSet = true;
            }
            if (userToBot.Contains("help") || message.Type != ActivityTypes.Message)
            {
                await base.MessageReceived(context, item);

                return;
            }

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

            if (string.IsNullOrEmpty(accessToken))
            {
                if (userToBot.Contains("login"))
                {
                    await context.Forward(new AzureAuthDialog(resourceId.Value), this.ResumeAfterAuth, message, CancellationToken.None);
                }
                else
                {
                    await this.Help(context, new LuisResult());
                }
            }
            else
            {
                if (string.IsNullOrEmpty(context.GetSubscriptionId()))
                {
                    await this.UseSubscriptionAsync(context, new LuisResult());
                }
                else
                {
                    await base.MessageReceived(context, item);
                }
            }
        }
        private static async Task CheckLongRunningOperationStatus <T>(IDialogContext context, RunbookJob automationJob, string accessToken,
                                                                      Func <string, string, string, string, string, bool, Task <T> > getOperationStatusAsync, Func <T, bool> completionCondition,
                                                                      Func <T, T, RunbookJob, string> getOperationStatusMessage, int delayBetweenPoolingInSeconds = 2)
        {
            var lastOperationStatus = default(T);

            do
            {
                var subscriptionId = context.GetSubscriptionId();

                var newOperationStatus = await getOperationStatusAsync(accessToken, subscriptionId, automationJob.ResourceGroupName, automationJob.AutomationAccountName, automationJob.JobId, true).ConfigureAwait(false);

                var message = getOperationStatusMessage(lastOperationStatus, newOperationStatus, automationJob);
                await context.NotifyUser(message);

                await Task.Delay(TimeSpan.FromSeconds(delayBetweenPoolingInSeconds)).ConfigureAwait(false);

                lastOperationStatus = newOperationStatus;
            }while (!completionCondition(lastOperationStatus));
        }
        public async Task StatusJobAsync(IDialogContext context, LuisResult result)
        {
            var accessToken = await context.GetAccessToken(resourceId.Value);

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

            var subscriptionId = context.GetSubscriptionId();

            IList <RunbookJob> automationJobs = context.GetAutomationJobs(subscriptionId);

            if (automationJobs != null && automationJobs.Any())
            {
                var messageBuilder = new StringBuilder();
                messageBuilder.AppendLine("|Id|Runbook|Start Time|End Time|Status|");
                messageBuilder.AppendLine("|---|---|---|---|---|");
                foreach (var job in automationJobs)
                {
                    var automationJob = await new AutomationDomain().GetAutomationJobAsync(accessToken, subscriptionId, job.ResourceGroupName, job.AutomationAccountName, job.JobId, configureAwait: false);
                    var startDateTime = automationJob.StartDateTime?.ToString("g") ?? string.Empty;
                    var endDateTime   = automationJob.EndDateTime?.ToString("g") ?? string.Empty;
                    var status        = automationJob.Status ?? string.Empty;
                    messageBuilder.AppendLine($"|{job.FriendlyJobId}|{automationJob.RunbookName}|{startDateTime}|{endDateTime}|{status}|");
                }

                await context.PostAsync(messageBuilder.ToString());
            }
            else
            {
                await context.PostAsync("No Runbook Jobs were created in the current session. To create a new Runbook Job type: Start Runbook.");
            }

            context.Done <string>(null);
        }
Exemple #10
0
        private async Task ProcessAllVirtualMachinesActionAsync(IDialogContext context, LuisResult result,
                                                                Operations operation, ResumeAfter <AllVirtualMachinesFormState> resume)
        {
            EntityRecommendation resourceGroupEntity;

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

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

            var subscriptionId = context.GetSubscriptionId();
            var availableVMs   = (await new VMDomain().ListVirtualMachinesAsync(accessToken, subscriptionId)).ToList();

            // retrieve the list of VMs that are in the correct power state
            var validPowerStates = VirtualMachineHelper.RetrieveValidPowerStateByOperation(operation);
            IEnumerable <VirtualMachine> candidateVMs = null;

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

                candidateVMs = availableVMs.Where(vm => vm.ResourceGroup.Equals(resourceGroup, StringComparison.InvariantCultureIgnoreCase)).ToList();

                if (candidateVMs == null || !candidateVMs.Any())
                {
                    var operationText = VirtualMachineHelper.RetrieveOperationTextByOperation(operation);
                    await context.PostAsync($"The {resourceGroup} resource group doesn't contain VMs or doesn't exist in the current subscription.");

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

                candidateVMs = candidateVMs.Where(vm => validPowerStates.Contains(vm.PowerState)).ToList();

                if (candidateVMs == null || !candidateVMs.Any())
                {
                    var operationText = VirtualMachineHelper.RetrieveOperationTextByOperation(operation);
                    await context.PostAsync($"No virtual machines that can be {operationText} were found in the {resourceGroup} resource group of the current subscription.");

                    context.Done <string>(null);
                    return;
                }
            }
            else
            {
                candidateVMs = availableVMs.Where(vm => validPowerStates.Contains(vm.PowerState)).ToList();

                if (!candidateVMs.Any())
                {
                    var operationText = VirtualMachineHelper.RetrieveOperationTextByOperation(operation);
                    await context.PostAsync($"No virtual machines that can be {operationText} were found in the current subscription.");

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

            // prompt the user to select a VM from the list
            var form = new FormDialog <AllVirtualMachinesFormState>(
                new AllVirtualMachinesFormState(candidateVMs, operation),
                VMForms.BuildAllVirtualMachinesForm,
                FormOptions.PromptInStart,
                null);

            context.Call(form, resume);
        }
Exemple #11
0
        private async Task ProcessVirtualMachineActionAsync(IDialogContext context, LuisResult result,
                                                            Operations operation, ResumeAfter <VirtualMachineFormState> resume)
        {
            EntityRecommendation virtualMachineEntity;

            // retrieve the list virtual machines from the subscription
            var accessToken = await context.GetAccessToken(resourceId.Value);

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

            var subscriptionId = context.GetSubscriptionId();
            var availableVMs   = (await new VMDomain().ListVirtualMachinesAsync(accessToken, subscriptionId)).ToList();

            // check if the user specified a virtual machine name in the command
            if (result.TryFindEntity("VirtualMachine", out virtualMachineEntity))
            {
                // obtain the name specified by the user - text in LUIS result is different
                var virtualMachineName = virtualMachineEntity.GetEntityOriginalText(result.Query);

                // ensure that the virtual machine exists in the subscription
                var selectedVM = availableVMs.FirstOrDefault(p => p.Name.Equals(virtualMachineName, StringComparison.InvariantCultureIgnoreCase));
                if (selectedVM == null)
                {
                    await context.PostAsync($"The '{virtualMachineName}' virtual machine was not found in the current subscription.");

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

                // ensure that the virtual machine is in the correct power state for the requested operation
                if ((operation == Operations.Start && (selectedVM.PowerState == VirtualMachinePowerState.Starting || selectedVM.PowerState == VirtualMachinePowerState.Running)) ||
                    (operation == Operations.Shutdown && (selectedVM.PowerState == VirtualMachinePowerState.Stopping || selectedVM.PowerState == VirtualMachinePowerState.Stopped)) ||
                    (operation == Operations.Stop && (selectedVM.PowerState == VirtualMachinePowerState.Deallocating || selectedVM.PowerState == VirtualMachinePowerState.Deallocated)))
                {
                    var powerState = selectedVM.PowerState.ToString().ToLower();
                    await context.PostAsync($"The '{virtualMachineName}' virtual machine is already {powerState}.");

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

                virtualMachineEntity.Entity = selectedVM.Name;
            }

            // retrieve the list of VMs that are in the correct power state
            var validPowerStates = VirtualMachineHelper.RetrieveValidPowerStateByOperation(operation);

            var candidateVMs = availableVMs.Where(vm => validPowerStates.Contains(vm.PowerState)).ToList();

            if (candidateVMs.Any())
            {
                // prompt the user to select a VM from the list
                var form = new FormDialog <VirtualMachineFormState>(
                    new VirtualMachineFormState(candidateVMs, operation),
                    VMForms.BuildVirtualMachinesForm,
                    FormOptions.PromptInStart,
                    result.Entities);

                context.Call(form, resume);
            }
            else
            {
                var operationText = VirtualMachineHelper.RetrieveOperationTextByOperation(operation);
                await context.PostAsync($"No virtual machines that can be {operationText} were found in the current subscription.");

                context.Done <string>(null);
                //context.Wait(this.MessageReceived);
            }
        }
        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);
            }
        }
        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);
            }
        }