/// <summary> /// Main method which is invoked on each conversation turn. /// </summary> /// <param name="turnContext"></param> /// <param name="cancellation"></param> /// <returns></returns> public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken)) { DialogContext dc = null; string adaptiveCardPath = string.Empty; //based upon the activity received, the decision needs to be made if a new dialog is created or an existing one is used. switch (turnContext.Activity.Type) { case ActivityTypes.Message: await ProcessCommandsAsync(turnContext, cancellationToken); break; case ActivityTypes.Event: if (turnContext.Activity.Name == "setUserIdEvent") { adaptiveCardPath = string.Format(Constants.AdaptiveCardPath, Constants.AdaptiveCards.WelcomeMessage.ToString()); await turnContext.SendActivityAsync(DialogHelpers.CreateReply(turnContext, adaptiveCardPath, true), cancellationToken); } else { dc = await _dialogs.CreateContextAsync(turnContext, cancellationToken); await dc.ContinueDialogAsync(cancellationToken); if (!turnContext.Responded) { await dc.BeginDialogAsync(Constants.RootDialogName, cancellationToken); } } break; case ActivityTypes.ContactRelationUpdate: adaptiveCardPath = string.Format(Constants.AdaptiveCardPath, Constants.AdaptiveCards.WelcomeMessage.ToString()); await turnContext.SendActivityAsync(DialogHelpers.CreateReply(turnContext, adaptiveCardPath, true), cancellationToken); break; case ActivityTypes.ConversationUpdate: foreach (var member in turnContext.Activity.MembersAdded) { if (member.Id != turnContext.Activity.Recipient.Id) { adaptiveCardPath = string.Format(Constants.AdaptiveCardPath, Constants.AdaptiveCards.WelcomeMessage.ToString()); await turnContext.SendActivityAsync(DialogHelpers.CreateReply(turnContext, adaptiveCardPath, true), cancellationToken); } } break; } }
/// <summary> /// This method gets called by the runtime. Use this method to add services to the container. /// </summary> /// <param name="services">The <see cref="IServiceCollection"/> specifies the contract for a collection of service descriptors.</param> /// <seealso cref="IStatePropertyAccessor{T}"/> /// <seealso cref="https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/dependency-injection"/> /// <seealso cref="https://docs.microsoft.com/en-us/azure/bot-service/bot-service-manage-channels?view=azure-bot-service-4.0"/> public void ConfigureServices(IServiceCollection services) { services.AddBot <BizTalkAdminBot>(options => { var secretKey = Configuration.GetSection("botFileSecret")?.Value; var botFilePath = Configuration.GetSection("botFilePath")?.Value; // Loads .bot configuration file and adds a singleton that your Bot can access through dependency injection. var botConfig = BotConfiguration.Load(botFilePath ?? @".\BizTalkAdminBot.bot", secretKey); services.AddSingleton(sp => botConfig ?? throw new InvalidOperationException($"The .bot config file could not be loaded. ({botConfig})")); // Retrieve current endpoint. var environment = _isProduction ? "production" : "development"; var service = botConfig.Services.Where(s => s.Type == "endpoint" && s.Name == environment).FirstOrDefault(); if (!(service is EndpointService endpointService)) { throw new InvalidOperationException($"The .bot file does not contain an endpoint with name '{environment}'."); } options.CredentialProvider = new SimpleCredentialProvider(endpointService.AppId, endpointService.AppPassword); // Creates a logger for the application to use. ILogger logger = _loggerFactory.CreateLogger <BizTalkAdminBot>(); // Catches any errors that occur during a conversation turn and logs them. options.OnTurnError = async(context, exception) => { logger.LogError($"Exception caught : {exception}"); string errorAdaptiveCardString = string.Format(Constants.AdaptiveCardPath, Constants.AdaptiveCards.ErrorMessage.ToString()); await context.SendActivityAsync(DialogHelpers.CreateReply(context, errorAdaptiveCardString, true)); }; // The Memory Storage used here is for local bot debugging only. When the bot // is restarted, everything stored in memory will be gone. IStorage dataStore = new MemoryStorage(); // For production bots use the Azure Blob or // Azure CosmosDB storage providers. For the Azure // based storage providers, add the Microsoft.Bot.Builder.Azure // Nuget package to your solution. That package is found at: // https://www.nuget.org/packages/Microsoft.Bot.Builder.Azure/ // Uncomment the following lines to use Azure Blob Storage // //Storage configuration name or ID from the .bot file. // const string StorageConfigurationId = "<STORAGE-NAME-OR-ID-FROM-BOT-FILE>"; // var blobConfig = botConfig.FindServiceByNameOrId(StorageConfigurationId); // if (!(blobConfig is BlobStorageService blobStorageConfig)) // { // throw new InvalidOperationException($"The .bot file does not contain an blob storage with name '{StorageConfigurationId}'."); // } // // Default container name. // const string DefaultBotContainer = "<DEFAULT-CONTAINER>"; // var storageContainer = string.IsNullOrWhiteSpace(blobStorageConfig.Container) ? DefaultBotContainer : blobStorageConfig.Container; // IStorage dataStore = new Microsoft.Bot.Builder.Azure.AzureBlobStorage(blobStorageConfig.ConnectionString, storageContainer); // Create Conversation State object. // The Conversation State object is where we persist anything at the conversation-scope. var conversationState = new ConversationState(dataStore); options.State.Add(conversationState); var userState = new UserState(dataStore); options.State.Add(userState); }); // Create and register state accesssors. // Acessors created here are passed into the IBot-derived class on every turn. services.AddSingleton <BizTalkAdminBotAccessors>(sp => { var options = sp.GetRequiredService <IOptions <BotFrameworkOptions> >().Value; if (options == null) { throw new InvalidOperationException("BotFrameworkOptions must be configured prior to setting up the state accessors"); } var conversationState = options.State.OfType <ConversationState>().FirstOrDefault(); if (conversationState == null) { throw new InvalidOperationException("ConversationState must be defined and added before adding conversation-scoped state accessors."); } var userState = options.State.OfType <UserState>().FirstOrDefault(); if (userState == null) { throw new InvalidOperationException("User State mjust be defined and added befor the conversation scoping"); } // Create the custom state accessor. // State accessors enable other components to read and write individual properties of state. var accessors = new BizTalkAdminBotAccessors(conversationState, userState) { CommandState = userState.CreateProperty <string>(BizTalkAdminBotAccessors.CommandStateName), ApplicationState = userState.CreateProperty <List <Application> >(BizTalkAdminBotAccessors.ApplicationStateName), HostState = userState.CreateProperty <List <Host> >(BizTalkAdminBotAccessors.HostStateName), OrchestrationState = userState.CreateProperty <List <Orchestration> >(BizTalkAdminBotAccessors.OrchestrationStateName), SendPortState = userState.CreateProperty <List <SendPort> >(BizTalkAdminBotAccessors.SendPortStateName), ReceiveLocationState = userState.CreateProperty <List <ReceiveLocation> >(BizTalkAdminBotAccessors.ReceiveLocationStateName), ConversationDialogState = userState.CreateProperty <DialogState>(BizTalkAdminBotAccessors.DialogStateName), FeedbackState = userState.CreateProperty <bool>(BizTalkAdminBotAccessors.FeedbackStateName), Reports = userState.CreateProperty <List <string> >(BizTalkAdminBotAccessors.ReportStateName) }; return(accessors); }); services.AddSingleton <IConfiguration>(Configuration); }
/// <summary> /// Method to process the text commands /// </summary> /// <param name="turnContext"></param> /// <param name="cancellationToken"></param> /// <returns></returns> private async Task <DialogTurnResult> ProcessStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken) { //Check if the User has already provided the feedback, if yes, then do not show the FeedBack card again. var isFeedbackProvided = await _accessors.FeedbackState.GetAsync(stepContext.Context, () => false, cancellationToken); BizTalkOperationApiHelper apiHelper; List <Application> applications = new List <Application>(); List <SendPort> sendPorts = new List <SendPort>(); List <ReceiveLocation> receiveLocations = new List <ReceiveLocation>(); List <string> reports = new List <string>(); BlobHelper blobHelper; //This works with only the ImBack type events sent by the emulator if (stepContext.Result != null) { var tokenResponse = stepContext.Result as TokenResponse; if (tokenResponse?.Token != null) { var parts = _accessors.CommandState.GetAsync(stepContext.Context, () => string.Empty, cancellationToken: cancellationToken).Result.Split(' '); string command = parts[0].ToLowerInvariant(); string adaptiveCardData; string operationCard = string.Empty; switch (command) { case "getallapplications": apiHelper = new BizTalkOperationApiHelper("getallapplications"); applications = await apiHelper.GetApplicationsAsync(); //string sampleAppListJson = GenericHelpers.ReadTextFromFile(@".\SampleMessages\GetApplications.json"); //List<Application> bizTalkApplications= JsonConvert.DeserializeObject<List<Application>>(sampleAppListJson); //Save the list of application object in the memory so as to see if the result was queried during the same session. //This saves the communication with the Logic App thus saving the number of round trips await _accessors.ApplicationState.SetAsync(stepContext.Context, applications, cancellationToken : cancellationToken); await _accessors.UserState.SaveChangesAsync(stepContext.Context, cancellationToken : cancellationToken); adaptiveCardData = AdaptiveCardsHelper.CreateGetApplicationsAdaptiveCard(applications); await stepContext.Context.SendActivityAsync(DialogHelpers.CreateReply(stepContext.Context, adaptiveCardData, false), cancellationToken : cancellationToken); await stepContext.Context.SendActivityAsync (DialogHelpers.CreateReply(stepContext.Context, string.Format(Constants.AdaptiveCardPath, (isFeedbackProvided ? Constants.AdaptiveCards.OperationMessageNoFB.ToString() : Constants.AdaptiveCards.OperationsMessage.ToString())) , true), cancellationToken); break; case "getorchbyapp": case "getsendportsbyapp": //Check the accessors to check if the ApplicationState contains a list of the application, if yes select it else, query the details from // On premises BizTalk System. This is done to avoid fetching the applications multiple times. applications = await _accessors.ApplicationState.GetAsync(stepContext.Context, () => new List <Application>(), cancellationToken : cancellationToken); if (applications.Count == 0 || applications == null) { apiHelper = new BizTalkOperationApiHelper("getallapplications"); applications = await apiHelper.GetApplicationsAsync(); //string appListJson = GenericHelpers.ReadTextFromFile(@".\SampleMessages\GetApplications.json"); //apps = JsonConvert.DeserializeObject<List<Application>>(appListJson); } adaptiveCardData = AdaptiveCardsHelper.CreateSelectApplicationListAdaptiveCard(applications, command); await stepContext.Context.SendActivityAsync(DialogHelpers.CreateReply(stepContext.Context, adaptiveCardData, false), cancellationToken : cancellationToken); break; case "gethosts": //Check if the Hosts were queried first. If the accessor contains the list then we do not call Logic App //And we save the state. Else we get the host form the State. List <Host> hosts = await _accessors.HostState.GetAsync(stepContext.Context, () => new List <Host>(), cancellationToken); if (hosts.Count == 0 || hosts == null) { apiHelper = new BizTalkOperationApiHelper("gethosts"); hosts = await apiHelper.GetHostsAsync(); } if (hosts.Count == 0) { await stepContext.Context.SendActivityAsync(string.Format(Constants.NotFoundMessage, "gethosts"), cancellationToken : cancellationToken); } else { await _accessors.HostState.SetAsync(stepContext.Context, hosts, cancellationToken); await _accessors.UserState.SaveChangesAsync(stepContext.Context, cancellationToken : cancellationToken); adaptiveCardData = AdaptiveCardsHelper.CreateGetHostsAdaptiveCard(hosts); await stepContext.Context.SendActivityAsync(DialogHelpers.CreateReply(stepContext.Context, adaptiveCardData, false), cancellationToken); } await stepContext.Context.SendActivityAsync (DialogHelpers.CreateReply(stepContext.Context, string.Format(Constants.AdaptiveCardPath, (isFeedbackProvided ? Constants.AdaptiveCards.OperationMessageNoFB.ToString() : Constants.AdaptiveCards.OperationsMessage.ToString())) , true), cancellationToken); break; case "getsuspendedinstances": apiHelper = new BizTalkOperationApiHelper("getsuspendedinstances"); List <Instance> instances = await apiHelper.GetInstancesAsync(); if (instances.Count > 0) { List <Instance> suspendedInstances = instances.Where(x => x.InstanceStatus == Constants.InstanceStatus.Suspended.ToString() || x.InstanceStatus == Constants.InstanceStatus.SuspendedNotResumable.ToString()).ToList(); if (suspendedInstances.Count() > 0) { string report = GenericHelpers.GetSuspendedInstancesReport(suspendedInstances); blobHelper = new BlobHelper(_configuration); string blobName = await blobHelper.UploadReportToBlobAsync(report, "SuspendedInstances"); adaptiveCardData = AdaptiveCardsHelper.CreateGetSuspendedInstancesAdaptiveCard(suspendedInstances); adaptiveCardData = adaptiveCardData.Replace(Constants.ReportDummyUrl, string.Format(Constants.ReportBaseUrl, _storageAccountKey, blobName)); await stepContext.Context.SendActivityAsync(DialogHelpers.CreateReply(stepContext.Context, adaptiveCardData, false), cancellationToken); reports = await _accessors.Reports.GetAsync(stepContext.Context, () => new List <string>(), cancellationToken); //If the reports does not contain the generated blob name, then add and save the list to the accessors. if (!reports.Contains(blobName)) { reports.Add(blobName); await _accessors.Reports.SetAsync(stepContext.Context, reports, cancellationToken); await _accessors.UserState.SaveChangesAsync(stepContext.Context, cancellationToken : cancellationToken); } } else { await stepContext.Context.SendActivityAsync("Sorry No Suspended Instances were found on the environment", cancellationToken : cancellationToken); } } else { await stepContext.Context.SendActivityAsync("Sorry No Instances were found on the environment", cancellationToken : cancellationToken); } await stepContext.Context.SendActivityAsync (DialogHelpers.CreateReply(stepContext.Context, string.Format(Constants.AdaptiveCardPath, (isFeedbackProvided ? Constants.AdaptiveCards.OperationMessageNoFB.ToString() : Constants.AdaptiveCards.OperationsMessage.ToString())) , true), cancellationToken); break; case "startsendport": //Check if the Send Ports are available in the Accessors, if they are available, we will not query the LA sendPorts = await _accessors.SendPortState.GetAsync(stepContext.Context, () => new List <SendPort>(), cancellationToken); if (sendPorts.Count == 0 || sendPorts == null) { apiHelper = new BizTalkOperationApiHelper("getsendportsbyapp"); sendPorts = await apiHelper.GetSendPortsAsync(); //save the list into SendPort State using Accessors } if (sendPorts.Count == 0) { await stepContext.Context.SendActivityAsync(string.Format(Constants.NotFoundMessage, "startsendport"), cancellationToken : cancellationToken); } else { //await _accessors.SendPortState.SetAsync(stepContext.Context, sendPorts, cancellationToken); //await _accessors.UserState.SaveChangesAsync(stepContext.Context, cancellationToken: cancellationToken); if (sendPorts.Where(x => x.Status == "Stopped").ToList().Count() > 0) { adaptiveCardData = AdaptiveCardsHelper.CreateSelectSendPortListAdaptiveCard(sendPorts.Where(x => x.Status == "Stopped").ToList(), "Please Select a send port to start", "startsendport"); await stepContext.Context.SendActivityAsync(DialogHelpers.CreateReply(stepContext.Context, adaptiveCardData, false), cancellationToken); } else { await stepContext.Context.SendActivityAsync("No Send Port is in Stopped State. Please Slect another option."); await stepContext.Context.SendActivityAsync (DialogHelpers.CreateReply(stepContext.Context, string.Format(Constants.AdaptiveCardPath, (isFeedbackProvided ? Constants.AdaptiveCards.OperationMessageNoFB.ToString() : Constants.AdaptiveCards.OperationsMessage.ToString())) , true), cancellationToken); } } break; case "stopsendport": //Check if the Send Ports are available in the Accessors, if they are available, we will not query the LA sendPorts = await _accessors.SendPortState.GetAsync(stepContext.Context, () => new List <SendPort>(), cancellationToken); if (sendPorts.Count == 0 || sendPorts == null) { apiHelper = new BizTalkOperationApiHelper("getsendportsbyapp"); sendPorts = await apiHelper.GetSendPortsAsync(); //save the list into SendPort State using Accessors } if (sendPorts.Count == 0) { await stepContext.Context.SendActivityAsync(string.Format(Constants.NotFoundMessage, "stopsendport"), cancellationToken : cancellationToken); } else { //await _accessors.SendPortState.SetAsync(stepContext.Context, sendPorts, cancellationToken); //await _accessors.UserState.SaveChangesAsync(stepContext.Context, cancellationToken: cancellationToken); if (sendPorts.Where(x => x.Status == "Started").ToList().Count() > 0) { adaptiveCardData = AdaptiveCardsHelper.CreateSelectSendPortListAdaptiveCard(sendPorts.Where(x => x.Status == "Started").ToList(), "Please Select a send port to stop", "stopsendport"); await stepContext.Context.SendActivityAsync(DialogHelpers.CreateReply(stepContext.Context, adaptiveCardData, false), cancellationToken); } else { await stepContext.Context.SendActivityAsync("No Send Port is in Started State. Please Slect another option."); await stepContext.Context.SendActivityAsync (DialogHelpers.CreateReply(stepContext.Context, string.Format(Constants.AdaptiveCardPath, (isFeedbackProvided ? Constants.AdaptiveCards.OperationMessageNoFB.ToString() : Constants.AdaptiveCards.OperationsMessage.ToString())) , true), cancellationToken); } } break; case "enablerl": receiveLocations = await _accessors.ReceiveLocationState.GetAsync(stepContext.Context, () => new List <ReceiveLocation>(), cancellationToken); if (receiveLocations.Count == 0 || receiveLocations == null) { apiHelper = new BizTalkOperationApiHelper("getrls"); receiveLocations = await apiHelper.GetReceiveLocationsAsync(); } if (receiveLocations.Count == 0) { await stepContext.Context.SendActivityAsync(string.Format(Constants.NotFoundMessage, "enablerl"), cancellationToken : cancellationToken); } else { //await _accessors.SendPortState.SetAsync(stepContext.Context, sendPorts, cancellationToken); //await _accessors.UserState.SaveChangesAsync(stepContext.Context, cancellationToken: cancellationToken); if (receiveLocations.Where(x => !x.Enable).ToList().Count() > 0) { adaptiveCardData = AdaptiveCardsHelper.CreateSelectReceiveLocationListAdaptiveCard(receiveLocations.Where(x => !x.Enable).ToList(), "Please Select a Receive Location To Enable", "enablerl"); await stepContext.Context.SendActivityAsync(DialogHelpers.CreateReply(stepContext.Context, adaptiveCardData, false), cancellationToken); } else { await stepContext.Context.SendActivityAsync("No Receive Location is in Disabled State. Please Slect another option."); await stepContext.Context.SendActivityAsync (DialogHelpers.CreateReply(stepContext.Context, string.Format(Constants.AdaptiveCardPath, (isFeedbackProvided ? Constants.AdaptiveCards.OperationMessageNoFB.ToString() : Constants.AdaptiveCards.OperationsMessage.ToString())) , true), cancellationToken); } } break; case "disablerl": receiveLocations = await _accessors.ReceiveLocationState.GetAsync(stepContext.Context, () => new List <ReceiveLocation>(), cancellationToken); if (receiveLocations.Count == 0 || receiveLocations == null) { apiHelper = new BizTalkOperationApiHelper("getrls"); receiveLocations = await apiHelper.GetReceiveLocationsAsync(); } if (receiveLocations.Count == 0) { await stepContext.Context.SendActivityAsync(string.Format(Constants.NotFoundMessage, "disablerl"), cancellationToken : cancellationToken); } else { //await _accessors.SendPortState.SetAsync(stepContext.Context, sendPorts, cancellationToken); //await _accessors.UserState.SaveChangesAsync(stepContext.Context, cancellationToken: cancellationToken); if (receiveLocations.Where(x => x.Enable).ToList().Count() > 0) { adaptiveCardData = AdaptiveCardsHelper.CreateSelectReceiveLocationListAdaptiveCard(receiveLocations.Where(x => x.Enable).ToList(), "Please Select a Receive Location To Disable", "disablerl"); await stepContext.Context.SendActivityAsync(DialogHelpers.CreateReply(stepContext.Context, adaptiveCardData, false), cancellationToken); } else { await stepContext.Context.SendActivityAsync("No Receive Location is in Enabled State. Please Slect another option."); await stepContext.Context.SendActivityAsync (DialogHelpers.CreateReply(stepContext.Context, string.Format(Constants.AdaptiveCardPath, (isFeedbackProvided ? Constants.AdaptiveCards.OperationMessageNoFB.ToString() : Constants.AdaptiveCards.OperationsMessage.ToString())) , true), cancellationToken); } } break; case "feedback": adaptiveCardData = string.Format(Constants.AdaptiveCardPath, Constants.AdaptiveCards.FeedBackCard.ToString()); await stepContext.Context.SendActivityAsync(DialogHelpers.CreateReply(stepContext.Context, adaptiveCardData, true), cancellationToken : cancellationToken); //await stepContext.Context.SendActivityAsync // (DialogHelpers.CreateReply(stepContext.Context, // string.Format(Constants.AdaptiveCardPath, (isFeedbackProvided ? Constants.AdaptiveCards.OperationMessageNoFB.ToString() : Constants.AdaptiveCards.OperationsMessage.ToString())) // ,true), cancellationToken); break; default: await stepContext.Context.SendActivityAsync (DialogHelpers.CreateReply(stepContext.Context, string.Format(Constants.AdaptiveCardPath, (isFeedbackProvided ? Constants.AdaptiveCards.OperationMessageNoFB.ToString() : Constants.AdaptiveCards.OperationsMessage.ToString())) , true), cancellationToken); break; } } } else { var token = JToken.Parse(stepContext.Context.Activity.ChannelData.ToString()); if (System.Convert.ToBoolean(token["postback"].Value <string>())) { JToken commandToken = JToken.Parse(stepContext.Context.Activity.Value.ToString()); string command = GenericHelpers.ParseToken(commandToken, "command"); string adaptiveCardData = string.Empty; string applicationName = string.Empty; switch (command) { case "getorchbyapp": // Check if the Orchestration list is available in the Irchestration State in Accessors. //If the list is there, we will not call the Logic APp else we call the Logic APp and save the //Orchestration List in the Orchestration State. List <Orchestration> orchestrations = await _accessors.OrchestrationState.GetAsync(stepContext.Context, () => new List <Orchestration>(), cancellationToken); if (orchestrations.Count == 0 || orchestrations == null) { apiHelper = new BizTalkOperationApiHelper("getorchbyapp"); orchestrations = await apiHelper.GetOrchestrationsAsync(); } if (orchestrations.Count == 0) { await stepContext.Context.SendActivityAsync(string.Format(Constants.NotFoundMessage, "getorchbyapp"), cancellationToken : cancellationToken); } else { await _accessors.OrchestrationState.SetAsync(stepContext.Context, orchestrations, cancellationToken); await _accessors.UserState.SaveChangesAsync(stepContext.Context, cancellationToken : cancellationToken); applicationName = commandToken["applicationChoiceSet"].Value <string>(); adaptiveCardData = AdaptiveCardsHelper.CreateGetOrchestrationsAdaptiveCard(orchestrations.Where(x => x.ApplicationName == applicationName).ToList(), applicationName); await stepContext.Context.SendActivityAsync(DialogHelpers.CreateReply(stepContext.Context, adaptiveCardData, false), cancellationToken); } break; case "getsendportsbyapp": //Check if the Send Ports are avaiable in the SendPOrtS STate using the accessors, if they are not, call the Logic APp to //Query the result sendPorts = await _accessors.SendPortState.GetAsync(stepContext.Context, () => new List <SendPort>(), cancellationToken); if (sendPorts.Count == 0 || sendPorts == null) { apiHelper = new BizTalkOperationApiHelper("getsendportsbyapp"); sendPorts = await apiHelper.GetSendPortsAsync(); //save the list into SendPort State using Accessors } if (sendPorts.Count == 0) { await stepContext.Context.SendActivityAsync(string.Format(Constants.NotFoundMessage, "getsendportsbyapp"), cancellationToken : cancellationToken); } else { //await _accessors.SendPortState.SetAsync(stepContext.Context, sendPorts, cancellationToken); //await _accessors.UserState.SaveChangesAsync(stepContext.Context, cancellationToken: cancellationToken); applicationName = commandToken["applicationChoiceSet"].Value <string>(); adaptiveCardData = AdaptiveCardsHelper.CreateGetSendPortsByAppAdaptiveCard(sendPorts.Where(x => x.ApplicationName == applicationName).ToList(), applicationName); await stepContext.Context.SendActivityAsync(DialogHelpers.CreateReply(stepContext.Context, adaptiveCardData, false), cancellationToken); } break; case "startsendport": string sendportName = commandToken["sendPortChoiceSet"].Value <string>(); apiHelper = new BizTalkOperationApiHelper("startsendport", sendportName); bool status = await apiHelper.ChangeSendportStateAsync(); string message = string.Empty; if (status) { message = "Operation Completed Successfully"; } else { message = "Operation Failed"; } await stepContext.Context.SendActivityAsync(message, cancellationToken : cancellationToken); break; case "stopsendport": string sendport = commandToken["sendPortChoiceSet"].Value <string>(); apiHelper = new BizTalkOperationApiHelper("stopsendport", sendport); bool opStatus = await apiHelper.ChangeSendportStateAsync(); string responsemessage = string.Empty; if (opStatus) { message = "Operation Completed Successfully"; } else { message = "Operation Failed"; } await stepContext.Context.SendActivityAsync(message, cancellationToken : cancellationToken); break; case "enablerl": string receiveLocation = commandToken["receiveLocationsChoiceSet"].Value <string>(); apiHelper = new BizTalkOperationApiHelper("getrls"); receiveLocations = await apiHelper.GetReceiveLocationsAsync(); string receivePort = receiveLocations.Where(x => x.Name == receiveLocation).FirstOrDefault().ReceivePortName; //Stop the RL now apiHelper = new BizTalkOperationApiHelper("enablerl", receiveLocation, receivePort); bool rlStatus = await apiHelper.ChangeReceiveLocationStateAsync(); if (rlStatus) { message = "Operation Completed Successfully"; } else { message = "Operation Failed"; } await stepContext.Context.SendActivityAsync(message, cancellationToken : cancellationToken); break; case "disablerl": string rl = commandToken["receiveLocationsChoiceSet"].Value <string>(); apiHelper = new BizTalkOperationApiHelper("getrls"); receiveLocations = await apiHelper.GetReceiveLocationsAsync(); string rp = receiveLocations.Where(x => x.Name == rl).FirstOrDefault().ReceivePortName; //Stop the RL now apiHelper = new BizTalkOperationApiHelper("disablerl", rl, rp); bool rlopStatus = await apiHelper.ChangeReceiveLocationStateAsync(); if (rlopStatus) { message = "Operation Completed Successfully"; } else { message = "Operation Failed"; } await stepContext.Context.SendActivityAsync(message, cancellationToken : cancellationToken); break; case "feedback": //Save the state that the user has provided the feedback. If Saved, this case will not executed again in the same session. if (!isFeedbackProvided) { await _accessors.FeedbackState.SetAsync(stepContext.Context, true, cancellationToken); await _accessors.UserState.SaveChangesAsync(stepContext.Context, cancellationToken : cancellationToken); isFeedbackProvided = true; } await stepContext.Context.SendActivityAsync("Thank You for the feedback."); break; default: await stepContext.Context.SendActivityAsync("Unable To Perform the task"); break; } await stepContext.Context.SendActivityAsync (DialogHelpers.CreateReply(stepContext.Context, string.Format(Constants.AdaptiveCardPath, (isFeedbackProvided ? Constants.AdaptiveCards.OperationMessageNoFB.ToString() : Constants.AdaptiveCards.OperationsMessage.ToString())) , true), cancellationToken); } else { await stepContext.Context.SendActivityAsync("We couldn't Sign you in. Please try again later"); } } await _accessors.CommandState.DeleteAsync(stepContext.Context, cancellationToken); return(await stepContext.EndDialogAsync(cancellationToken : cancellationToken)); }
/// <summary> /// This method makes descision based upon the actual command received from the user. /// </summary> /// <param name="turnContext"></param> /// <param name="cancellationToken"></param> /// <returns></returns> private async Task <DialogContext> ProcessCommandsAsync(ITurnContext turnContext, CancellationToken cancellationToken) { //Create the dialog context for the current turn var dc = await _dialogs.CreateContextAsync(turnContext, cancellationToken); string adaptiveCardData; string command = turnContext.Activity.Text; // Based upon the parse command different logic will be called to construct the reply activities switch (command) { case "logoff": case "signoff": case "signout": case "logout": var botAdapter = turnContext.Adapter as BotFrameworkAdapter; //Signout and cancel the token saved in the Azure Bot Service await botAdapter.SignOutUserAsync(turnContext, Constants.OAuthConnectionName, cancellationToken : cancellationToken); //Tell the user that they are signed out adaptiveCardData = string.Format(Constants.AdaptiveCardPath, Constants.AdaptiveCards.SignOutMessage.ToString()); await turnContext.SendActivityAsync(DialogHelpers.CreateReply(turnContext, adaptiveCardData, true), cancellationToken); //end the dialog as the user is signed out. A new login will begin the new dialog. await dc.EndDialogAsync(Constants.RootDialogName, cancellationToken); await _accessors.ApplicationState.DeleteAsync(turnContext, cancellationToken : cancellationToken); await _accessors.HostState.DeleteAsync(turnContext, cancellationToken); await _accessors.OrchestrationState.DeleteAsync(turnContext, cancellationToken); await _accessors.SendPortState.DeleteAsync(turnContext, cancellationToken); await _accessors.FeedbackState.DeleteAsync(turnContext, cancellationToken); List <string> reports = await _accessors.Reports.GetAsync(turnContext, () => new List <string>(), cancellationToken); await _accessors.Reports.DeleteAsync(turnContext, cancellationToken : cancellationToken); await _accessors.UserState.SaveChangesAsync(turnContext, cancellationToken : cancellationToken); //If Get Suspended/Tracked Instances operation was run, delete the blobs in the storage account if (reports.Count() > 0) { BlobHelper blobHelper = new BlobHelper(_configuration); foreach (string report in reports) { await blobHelper.DeleteReportBlobAsync(report); } } break; case "help": adaptiveCardData = string.Format(Constants.AdaptiveCardPath, Constants.AdaptiveCards.HelpMessage.ToString()); await turnContext.SendActivityAsync(DialogHelpers.CreateReply(turnContext, adaptiveCardData, true), cancellationToken); break; default: await dc.ContinueDialogAsync(cancellationToken); if (!turnContext.Responded) { await dc.BeginDialogAsync(Constants.RootDialogName, cancellationToken : cancellationToken); } break; } return(dc); }