//private Microsoft.Bot.Connector.Activity message = null;
        private async Task EnsureAuthentication(IDialogContext context, Microsoft.Bot.Connector.Activity activity)
        {
            string token = null;

            if (activity.ChannelId.Equals("cortana", StringComparison.InvariantCultureIgnoreCase))
            {
                token = await context.GetAccessToken(string.Empty);
            }
            else
            {
                token = await context.GetAccessToken(AuthSettings.Scopes);
            }

            if (string.IsNullOrEmpty(token))
            {
                if (activity.ChannelId.Equals("cortana", StringComparison.InvariantCultureIgnoreCase))
                {
                    //Cortana channel uses Connected Service for authentication, it has to be authorized to use cortana, we should not get here...
                    throw new InvalidOperationException("Cortana channel has to be used with Conencted Service Account");
                }
                else
                {
                    //message = activity;
                    await context.Forward(new AzureAuthDialog(AuthSettings.Scopes), this.ResumeAfterAuth, context.Activity, CancellationToken.None);
                }
            }
            else
            {
                //await MessageReceived(context, Awaitable.FromItem<Microsoft.Bot.Connector.Activity>(activity));
                await base.MessageReceived(context, Awaitable.FromItem <Microsoft.Bot.Connector.Activity>(activity));
            }
        }
示例#2
0
        public virtual async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> item)
        {
            var message = await item;


            if (string.Equals(message.Text, "help", StringComparison.OrdinalIgnoreCase))
            {
                await context.PostAsync("Hi! I'm a simple OneDrive for Business bot. Just type the keywords you are looking for and I'll search your OneDrive for Business for files.");

                context.Wait(this.MessageReceivedAsync);
            }
            else if (string.Equals(message.Text, "logout", StringComparison.OrdinalIgnoreCase))
            {
                await context.Logout();

                context.Wait(this.MessageReceivedAsync);
            }
            else
            {   //Assume this is a query for OneDrive so let's get an access token
                if (string.IsNullOrEmpty(await context.GetAccessToken(AuthSettings.Scopes)))
                {
                    //We can't get an access token, so let's try to log the user in
                    await context.Forward(new AzureAuthDialog(AuthSettings.Scopes), this.ResumeAfterAuth, message, CancellationToken.None);
                }
                else
                {
                    var files = await SearchOneDrive(message.Text, await context.GetAccessToken(AuthSettings.Scopes));

                    PromptDialog.Choice(context, FileSelectResult, files, "Which file do you want?", null, 3, PromptStyle.PerLine);
                }
            }
        }
        public async Task MessageReceivedAsync(IDialogContext context, IAwaitable <Message> item)
        {
            var message = await item;

            context.UserData.SetValue(ContextConstants.CurrentMessageFromKey, message.From);
            context.UserData.SetValue(ContextConstants.CurrentMessageToKey, message.To);
            // await context.PostAsync(message.Text);


            if (string.Equals(message.Text, "help", StringComparison.OrdinalIgnoreCase))
            {
                await context.PostAsync("Hello...just give me the name of someone in your company and I will give you their full organization structure.");

                context.Wait(this.MessageReceivedAsync);
            }
            else if (string.Equals(message.Text, "logout", StringComparison.OrdinalIgnoreCase))
            {
                await context.Logout();

                context.Wait(this.MessageReceivedAsync);
            }
            else
            {   //Assume this is a query for organization structure
                if (string.IsNullOrEmpty(await context.GetAccessToken(resourceId.Value)))
                {
                    //We can't get an access token, so let's try to log the user in
                    await context.Forward(new AzureAuthDialog(resourceId.Value), this.ResumeAfterAuth, message, CancellationToken.None);
                }
                else
                {
                    // Search for the user
                    var results = await searchUser(message.Text, await context.GetAccessToken(resourceId.Value));

                    if (results.Count == 0)
                    {
                        //none found
                        await context.PostAsync("No results found...try checking the spelling or just type the beginning of the name (ex: Barak Oba).");

                        context.Wait(this.MessageReceivedAsync);
                    }
                    else if (results.Count > 1)
                    {
                        //let them choose
                        PromptDialog.Choice(context, userSelected, results, "Which user do you want to explore?");
                    }
                    else
                    {
                        //process the org for the user
                        var user = results[0];
                        await outputUser(context, user);
                    }
                }
            }
        }
示例#4
0
        public virtual async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> item)
        {
            var message = await item;

            if (message.Text == "logon")
            {
                //endpoint v2
                if (string.IsNullOrEmpty(await context.GetAccessToken(AuthSettings.Scopes)))
                {
                    await context.Forward(new AzureAuthDialog(AuthSettings.Scopes), this.ResumeAfterAuth, message, CancellationToken.None);
                }
                else
                {
                    context.Wait(MessageReceivedAsync);
                }
            }
            else if (message.Text == "logout")
            {
                await context.Logout();

                context.Wait(this.MessageReceivedAsync);
            }
            else
            {
                AuthResult authResult;
                context.UserData.TryGetValue(ContextConstants.AuthResultKey, out authResult);
                if (authResult != null)
                {
                    SAPLuisDialog dialog = new SAPLuisDialog();
                    try
                    {
                        await context.Forward(dialog, this.resumeFunc, message, CancellationToken.None);
                    }
                    catch (Exception e)
                    {
                    }
                }
                else
                {
                    await context.PostAsync("I don't Interact with Strangers,..");

                    if (string.IsNullOrEmpty(await context.GetAccessToken(AuthSettings.Scopes)))
                    {
                        await context.Forward(new AzureAuthDialog(AuthSettings.Scopes), this.ResumeAfterAuth, message, CancellationToken.None);
                    }
                    else
                    {
                        context.Wait(MessageReceivedAsync);
                    }
                    //  context.Wait(MessageReceivedAsync);
                }
            }
        }
        /// <summary>
        /// Checks if we are able to get an access token. If not, we prompt for a login
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        protected virtual async Task CheckForLogin(IDialogContext context, IMessageActivity msg)
        {
            try
            {
                string token;
                if (resourceId != null)
                {
                    token = await context.GetAccessToken(resourceId);
                }
                else
                {
                    token = await context.GetAccessToken(scopes);
                }

                if (string.IsNullOrEmpty(token))
                {
                    if (msg.Text != null &&
                        CancellationWords.GetCancellationWords().Contains(msg.Text.ToUpper()))
                    {
                        context.Done(string.Empty);
                    }
                    else
                    {
                        var resumptionCookie = new ResumptionCookie(msg);

                        string authenticationUrl;
                        if (resourceId != null)
                        {
                            authenticationUrl = await AzureActiveDirectoryHelper.GetAuthUrlAsync(resumptionCookie, resourceId);
                        }
                        else
                        {
                            authenticationUrl = await AzureActiveDirectoryHelper.GetAuthUrlAsync(resumptionCookie, scopes);
                        }

                        await PromptToLogin(context, msg, authenticationUrl);

                        context.Wait(this.MessageReceivedAsync);
                    }
                }
                else
                {
                    context.Done(string.Empty);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
示例#6
0
        private async Task UpdateTaskProgressAsync(IDialogContext context,
                                                   IAwaitable <bool> result, int percentComplete)
        {
            var confirm   = await result;
            var operation = context.ConversationData.Get <QueryOperation>("TaskOperation");

            // Get the task.
            var task = operation.GetContextObjectAs <PlanTask>();

            if (confirm)
            {
                var httpClient  = new HttpClient();
                var accessToken = await context.GetAccessToken();

                // Update the task.
                await context.PostAsync("Updating task...");

                var response = await httpClient.MSGraphPATCH(accessToken,
                                                             $"https://graph.microsoft.com/beta/{operation.Endpoint}", new
                {
                    PercentComplete = percentComplete
                }, task.ETag);

                await context.PostAsync(response? "Task updated!" : "Update failed!");

                // Show operations.
                await ShowOperationsAsync(context);
            }
            else
            {
                // Show task operations.
                await ShowTaskOperationsAsync(context, operation);
            }
        }
        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);
        }
        private async Task SelectWorksheet_FormComplete(IDialogContext context, IAwaitable <SelectWorksheetForm> result)
        {
            SelectWorksheetForm form = null;

            try
            {
                form = await result;
            }
            catch
            {
            }

            if (form != null)
            {
                // Get access token to see if user is authenticated
                ServicesHelper.AccessToken = await context.GetAccessToken(ConfigurationManager.AppSettings["ActiveDirectory.ResourceId"]);

                // Select worksheet
                await WorksheetWorker.DoSelectWorksheetAsync(context, form.WorksheetName);

                context.Done <bool>(true);
            }
            else
            {
                await context.PostAsync("Okay! I will just sit tight until you tell me what to do");

                context.Done <bool>(false);
            }
        }
示例#9
0
        private async Task ResumeAfterAuth(IDialogContext context, IAwaitable <string> result)
        {
            var        message = await result;
            AuthResult lResult = result as AuthResult;

            MessagesController.ConverastionalUserList[index].Token = await context.GetAccessToken(AuthSettings.Scopes);

            await context.PostAsync(message);

            await getCRMContact();

            #region CRM Knowledge Search
            List <Attachment> kbaList = await SearchKB();

            if (kbaList.Count > 0)
            {
                var reply = context.MakeMessage();

                reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                reply.Attachments      = kbaList;

                await context.PostAsync("I found some Knowledge Articles: ");

                await context.PostAsync(reply);

                context.Wait(this.MessageReceivedAsync);
            }
            else
            {
                await context.PostAsync("I couldn't find anything :(");

                context.Wait(this.MessageReceivedAsync);
            }
            #endregion
        }
示例#10
0
        /// <summary>
        /// Processes messages received on new thread
        /// </summary>
        /// <param name="context">IDialogContext</param>
        /// <param name="item">Awaitable IMessageActivity</param>
        /// <returns>Task</returns>
        public async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> item)
        {
            var token = await context.GetAccessToken();

            // Get the users profile photo from the Microsoft Graph
            //var bytes = await new HttpClient().GetStreamWithAuthAsync(token, "https://graph.microsoft.com/v1.0/me/photo/$value");
            byte[] bytes;
            var    client = new HttpClient();

            client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
            client.DefaultRequestHeaders.Add("Accept", "application/json");
            using (var response = await client.GetAsync("https://graph.microsoft.com/v1.0/me/photo/$value"))
            {
                if (response.IsSuccessStatusCode)
                {
                    var stream = await response.Content.ReadAsStreamAsync();

                    bytes = new byte[stream.Length];
                    stream.Read(bytes, 0, (int)stream.Length);

                    var pic = "data:image/png;base64," + Convert.ToBase64String(bytes);

                    // Output the picture as a base64 encoded string
                    var msg = context.MakeMessage();
                    msg.Text = "Check it out...I got your picture using the Microsoft Graph!";
                    msg.Attachments.Add(new Attachment("image/png", pic));
                    await context.PostAsync(msg);
                }
            }
        }
示例#11
0
文件: VMDialog.cs 项目: DVDYKC/VAOps
        private async Task ProcessAllVirtualMachinesFormComplete(IDialogContext context, IAwaitable <AllVirtualMachinesFormState> result,
                                                                 Func <string, string, string, string, Task <bool> > operationHandler, Func <string, string> preMessageHandler,
                                                                 Func <bool, string, string> notifyLongRunningOperationHandler)
        {
            try
            {
                var allVirtualMachineFormState = await result;

                await context.PostAsync(preMessageHandler(allVirtualMachineFormState.VirtualMachines));

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

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

                Parallel.ForEach(
                    allVirtualMachineFormState.AvailableVMs,
                    vm =>
                {
                    operationHandler(accessToken, vm.SubscriptionId, vm.ResourceGroup, vm.Name)
                    .NotifyLongRunningOperation(context, notifyLongRunningOperationHandler, vm.Name);
                });
            }
            catch (FormCanceledException <AllVirtualMachinesFormState> )
            {
                await context.PostAsync("You have canceled the operation. What would you like to do next?");
            }

            context.Done <string>(null);
        }
示例#12
0
        protected override async Task MessageReceived(IDialogContext context, IAwaitable <IMessageActivity> item)
        {
            var message = await item;

            // Get access token to see if user is authenticated
            ServicesHelper.AccessToken = await context.GetAccessToken(ConfigurationManager.AppSettings["ActiveDirectory.ResourceId"]);

            if (string.IsNullOrEmpty(ServicesHelper.AccessToken))
            {
                // Start authentication dialog
                await context.Forward(new AzureAuthDialog(ConfigurationManager.AppSettings["ActiveDirectory.ResourceId"]), this.ResumeAfterAuth, message, CancellationToken.None);
            }
            else if (message.Text == "logout")
            {
                // Process logout message
                await context.Logout();

                context.Wait(this.MessageReceived);
            }
            else
            {
                // Process incoming message
                await base.MessageReceived(context, item);
            }
        }
示例#13
0
        private async Task LogIn(IDialogContext context, Message msg)
        {
            try
            {
                string token = await context.GetAccessToken();

                if (string.IsNullOrEmpty(token))
                {
                    var resumptionCookie = new ResumptionCookie(msg);

                    var authenticationUrl = await AzureActiveDirectoryHelper.GetAuthUrlAsync(resumptionCookie);



                    await context.PostAsync($"You must be authenticated before you can proceed. Please, click [here]({authenticationUrl}) to log into your account.");

                    context.Wait(this.MessageReceivedAsync);
                }
                else
                {
                    context.Done(string.Empty);
                }
            }catch (Exception ex)
            {
                throw ex;
            }
        }
        private async Task GetWebInfo(IDialogContext context, IAwaitable <AskForUrlQuery> result)
        {
            var formResults = await result;
            var url         = formResults.Url;

            if (context.Activity.ChannelId == "skype")
            {
                url = Helpers.ParseAnchorTag(formResults.Url);
            }

            await context.GetAccessToken(url);

            context.UserData.TryGetValue(ContextConstants.AuthResultKey, out _authResult);

            var returnedItems = SharePointInfo.GetWebProperties(_authResult, url);

            foreach (var answer in returnedItems)
            {
                var message = answer;
                await context.PostAsync(message);
            }
            var finalMessage = $"What's next?";
            await context.PostAsync(finalMessage);

            context.Wait(MessageReceived);
        }
        private async Task AfterUrlProvided(IDialogContext context, IAwaitable <CreateSiteCollectionQuery> result)
        {
            var formResults = await result;

            context.UserData.TryGetValue("ResourceId", out _resourceId);
            var tenantUrl = $"https://{_resourceId}-admin.sharepoint.com";

            WebApiApplication.Telemetry.TrackTrace(context.CreateTraceTelemetry(nameof(AfterUrlProvided), new Dictionary <string, string> {
                { "Getting admin site:", tenantUrl }
            }));
            await context.GetAccessToken(tenantUrl);

            context.UserData.TryGetValue(ContextConstants.AuthResultKey, out _authResult);
            var success = Create.CreateSiteColleciton(_authResult, formResults, tenantUrl, _resourceId);

            if (success)
            {
                string message = $"Site Collection creation request send. What's next?";
                await context.PostAsync(message);
            }
            else
            {
                WebApiApplication.Telemetry.TrackTrace(context.CreateTraceTelemetry(nameof(AfterUrlProvided), new Dictionary <string, string> {
                    { "Site Collection creation error:", JsonConvert.SerializeObject(result) }
                }));
                string message = $"Sorry something went wrong. Please try again later.";
                await context.PostAsync(message);
            }

            context.Wait(MessageReceived);
        }
示例#16
0
        public async Task Help(IDialogContext context, LuisResult result)
        {
            string message     = "";
            var    accessToken = await context.GetAccessToken(resourceId.Value);

            if (string.IsNullOrEmpty(accessToken))
            {
                message += $"Hello!\n\n";
            }
            message += "I can help you: \n";
            message += $"* List, Switch and Select an Azure subscription\n";
            message += $"* List, Start, Shutdown (power off your VM, still incurring compute charges), and Stop (deallocates your VM, no charges) your virtual machines\n";
            message += $"* List your automation accounts and your runbooks\n";
            message += $"* Start a runbook, get the description of a runbook, get the status and output of automation jobs\n";
            message += $"* Login and Logout of an Azure Subscription\n\n";

            if (string.IsNullOrEmpty(accessToken))
            {
                message += $"By using me, you agree to the Microsoft Privacy Statement and Microsoft Services Agreement on http://aka.ms/AzureBot \n\n";
                message += $"Please type **login** to interact with me for the first time.";
            }


            await context.PostAsync(message);

            context.Wait(this.MessageReceived);
        }
示例#17
0
        public async Task None(IDialogContext context, LuisResult result)
        {
            var factory = new DialogFactory();
            AzureBotLuisDialog <string> dialog = await factory.Create(result.Query);

            if (dialog != null)
            {
                var message = context.MakeMessage();
                message.Text = userToBot;

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

                if (string.IsNullOrEmpty(accessToken))
                {
                    return;
                }
                await context.Forward(dialog, this.ResumeAfterForward, message, CancellationToken.None);
            }
            else
            {
                string message = $"Sorry, I did not understand '{result.Query}'. Type 'help' if you need assistance.";

                await context.PostAsync(message);

                context.Wait(MessageReceived);
            }
        }
示例#18
0
        private async Task OnDeleteTaskDialogResume(IDialogContext context,
                                                    IAwaitable <bool> result)
        {
            var confirm   = await result;
            var operation = context.ConversationData.Get <QueryOperation>("TaskOperation");

            // Get the task.
            var task = operation.GetContextObjectAs <PlanTask>();

            if (confirm)
            {
                var httpClient  = new HttpClient();
                var accessToken = await context.GetAccessToken();

                // Delete the task.
                await context.PostAsync("Deleting task...");

                var response = await httpClient.MSGraphDELETE(accessToken,
                                                              $"https://graph.microsoft.com/beta/{operation.Endpoint}", task.ETag);

                await context.PostAsync(response? "Task deleted!" : "Delete failed!");

                // Navigating up to parent, pop the level and then pop the
                // last query on the parent.
                context.NavPopLevel();
                context.NavPopItem();
                await ShowOperationsAsync(context);
            }
            else
            {
                // Show task operations.
                await ShowTaskOperationsAsync(context, operation);
            }
        }
示例#19
0
        public async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> item)
        {
            var message = await item;


            var token = await context.GetAccessToken("https://graph.microsoft.com/");

            if (string.IsNullOrEmpty(token))
            {
                await context.Forward(new AzureAuthDialog("https://graph.microsoft.com/"), this.resumeAfterAuth, message, CancellationToken.None);
            }
            else
            {
                var client = GetClient(token);
                await client.Me.Request().UpdateAsync(new User
                {
                    PasswordProfile = new PasswordProfile
                    {
                        Password = message.Text,
                        ForceChangePasswordNextSignIn = false
                    },
                });

                await context.PostAsync($"Password has already changed");

                context.Wait(MessageReceivedAsync);
            }
        }
示例#20
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);
        }
示例#21
0
        private async Task <HttpClient> GetClient(bool isGet = false, int paging = 0)
        {
            HttpClient client = new HttpClient(new HttpClientHandler()
            {
                AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
            });

            client.BaseAddress = new Uri(ConfigurationManager.AppSettings["D365Url"]);

            client.DefaultRequestHeaders.Authorization =
                new AuthenticationHeaderValue("Bearer",
                                              await context.GetAccessToken(ConfigurationManager.AppSettings["D365Url"]));

            if (isGet)
            {
                client.DefaultRequestHeaders.Add(
                    "Accept", "application/json");
                client.DefaultRequestHeaders.Add(
                    "Prefer", "odata.include-annotations=\"*\"");
            }
            if (paging != 0)
            {
                client.DefaultRequestHeaders.Add(
                    "Preference-Applied", $"odata.maxpagesize={paging}");
            }

            return(client);
        }
示例#22
0
文件: VMDialog.cs 项目: DVDYKC/VAOps
        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);
        }
示例#23
0
        public async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> input)
        {
            var msg = await input;

            // Try to get a token
            var token = await context.GetAccessToken("https://graph.microsoft.com");

            if (!String.IsNullOrEmpty(token))
            {
                // Token request was successful so send back to caller
                context.Done(token);
            }
            else
            {
                // Forward to AzureAuthDialog to manage auth process
                await context.Forward(new AzureAuthDialog("https://graph.microsoft.com", "Wait a second...I don't know who you are...please sign-in:"), async (IDialogContext authContext, IAwaitable <string> authResult) => {
                    // Resume after auth
                    var message = await authResult;
                    await authContext.PostAsync(message);

                    // Get the token
                    var t = await authContext.GetAccessToken("https://graph.microsoft.com");
                    authContext.Done(t);
                }, msg, CancellationToken.None);
            }
        }
示例#24
0
        private async Task OpenWorkbookFormComplete(IDialogContext context, IAwaitable <OpenWorkbookForm> result)
        {
            OpenWorkbookForm form = null;

            try
            {
                form = await result;
            }
            catch
            {
                await context.PostAsync("You canceled opening a workbook. No problem! I can move on to something else");

                return;
            }

            if (form != null)
            {
                // Get access token to see if user is authenticated
                ServicesHelper.AccessToken = await context.GetAccessToken(ConfigurationManager.AppSettings["ActiveDirectory.ResourceId"]);

                // Open workbook
                await WorkbookWorker.DoOpenWorkbookAsync(context, form.WorkbookName);
            }
            else
            {
                await context.PostAsync("Sorry, something went wrong (form is empty)");
            }
            context.Wait(MessageReceived);
        }
        private async Task ReindexSite(IDialogContext context, IAwaitable <AskForUrlQuery> result)
        {
            var formResults = await result;
            var url         = formResults.Url;

            if (context.Activity.ChannelId == "skype")
            {
                url = Helpers.ParseAnchorTag(formResults.Url);
            }

            await context.GetAccessToken(url);

            context.UserData.TryGetValue(ContextConstants.AuthResultKey, out _authResult);

            var success = SharePointInfo.ReIndexSiteCollection(_authResult, url);

            if (success)
            {
                string message = $"Reindexing triggered. What's next?";
                await context.PostAsync(message);
            }
            else
            {
                string message = $"Request for reindex went wrong";
                await context.PostAsync(message);
            }
            context.Wait(MessageReceived);
        }
示例#26
0
#pragma warning disable 1998
        public async Task ShowTextDialogAsync(IDialogContext context, IAwaitable <IMessageActivity> item)
#pragma warning restore 1998
        {
            // Get entities.
            var accessToken = await context.GetAccessToken();

            _entities = await GetEntitesAsync(context, accessToken);

            // No matches, retry.
            if (_entities.Count == 0)
            {
                Retry(context);
            }
            else
            {
                // If the entities are below five, let the user pick
                // one right away. If not, let the user do a lookup.
                if (_entities.Count <= 5)
                {
                    ShowChoices(context, _entities, true);
                }
                else
                {
                    PromptDialog.Text(context, OnTextDialogResumeAsync, LookupPrompt);
                }
            }
        }
示例#27
0
        private async Task OpenWorkbook_FormComplete(IDialogContext context, IAwaitable <OpenWorkbookForm> result)
        {
            OpenWorkbookForm form = null;

            try
            {
                form = await result;
            }
            catch
            {
            }

            if (form != null)
            {
                // Get access token to see if user is authenticated
                ServicesHelper.AccessToken = await context.GetAccessToken(ConfigurationManager.AppSettings["ActiveDirectory.ResourceId"]);

                // Open the workbook
                await WorkbookWorker.DoOpenWorkbookAsync(context, form.WorkbookName);

                context.Done <bool>(true);
            }
            else
            {
                await context.PostAsync("Okay! I will just sit tight until you tell me which workbook we should work with");

                context.Done <bool>(false);
            }
        }
示例#28
0
        private async Task LogIn(IDialogContext context, IMessageActivity msg, string resourceId)
        {
            try
            {
                string token = await context.GetAccessToken(resourceId);

                if (string.IsNullOrEmpty(token))
                {
                    if (msg.Text != null &&
                        CancellationWords.GetCancellationWords().Contains(msg.Text.ToUpper()))
                    {
                        context.Done(string.Empty);
                    }
                    else
                    {
                        var resumptionCookie = new ResumptionCookie(msg);

                        var authenticationUrl = await AzureActiveDirectoryHelper.GetAuthUrlAsync(resumptionCookie, resourceId);

                        await context.PostAsync($"You must be authenticated before you can proceed. Please, click [here]({authenticationUrl}) to log into your account.");

                        context.Wait(this.MessageReceivedAsync);
                    }
                }
                else
                {
                    context.Done(string.Empty);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <object> result)
        {
            var message = await result as Activity;

            // Check authentication
            if (string.IsNullOrEmpty(await context.GetAccessToken(ConfigurationManager.AppSettings["ActiveDirectory.ResourceId"])))
            {
                // Run authentication dialog
                await context.Forward(new AzureAuthDialog(ConfigurationManager.AppSettings["ActiveDirectory.ResourceId"]), this.ResumeAfterAuth, message, CancellationToken.None);
            }
            else
            {
                using (var scope = WebApiApplication.Container.BeginLifetimeScope())
                {
                    // Resolve IEventService to concrete type. Pass IDialogContext object to constructor
                    IEventService service = scope.Resolve <IEventService>(new TypedParameter(typeof(IDialogContext), context));
                    var           events  = await service.GetEvents();

                    foreach (var @event in events)
                    {
                        await context.PostAsync($"{@event.Start.DateTime}-{@event.End.DateTime}: {@event.Subject}");
                    }
                }
            }
        }
        private async Task outputUser(IDialogContext context, Models.User user)
        {
            //get management structure and direct reports
            user.Manager = await getManager(user, await context.GetAccessToken(resourceId.Value));

            user.DirectReports = await getDirectReports(user, await context.GetAccessToken(resourceId.Value));

            //flatten structure
            var pointer            = user;
            List <Models.User> org = new List <Models.User>();

            org.Add(pointer.Clone());
            while (pointer.Manager != null)
            {
                org.Insert(0, pointer.Manager.Clone());
                pointer = pointer.Manager;
            }
            int i = 0;

            for (i = 0; i < org.Count; i++)
            {
                if (i == 0)
                {
                    org[i].IndentedDisplayName = org[i].DisplayName;
                }
                else if (i == org.Count - 1)
                {
                    org[i].IndentedDisplayName = indent((i - 1) * 2) + "* **" + org[i].DisplayName + "**";
                }
                else
                {
                    org[i].IndentedDisplayName = indent((i - 1) * 2) + "* " + org[i].DisplayName;
                }
            }
            foreach (var directReport in user.DirectReports)
            {
                var dr = directReport.Clone();
                dr.IndentedDisplayName = indent(i * 2) + "* " + dr.DisplayName;
                org.Add(dr);
            }
            var result = String.Join("\n\n", org.Select(x => x.IndentedDisplayName));

            //check for any results
            await context.PostAsync(result);

            context.Wait(MessageReceivedAsync);
        }