Chat Bot With SharePoint Authentication - Part Two

Highlights of the article series

  • How to register app in SharePoint
  • How to access SharePoint data in Chat bot

Prerequisite

Code file is attached with article; you can pull code from GitHub also.

In the previous part of the article, we have completed initial setup. In this part of the article, we will implement chat bot which will access data from SharePoint.

Request flow

In this diagram, I have mentioned sequence numbers to identify the flow.

 

  1. User will start a conversation with bot by greeting it; i.e., saying ‘Hi’ or ‘Hello’.
  2. We have already developed a bot application to consume LUIS service in this article. For SharePoint related communication, we will add SharePointController and SharePointDialog in our bot application.

 

 

 

SharePointController.cs

I have updated Post( ) method to invoke SharePointDialog with parameter activity.

  1. public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
  2. {  
  3.    if (activity.Type == ActivityTypes.Message)  
  4.    {  
  5.       await Conversation.SendAsync(activity, () => new Dialogs.SharePointDialog(activity));  
  6.    }  
  7.    else
  8.    { 
  9.       HandleSystemMessage(activity);  
  10.    }  
  11.    var response = Request.CreateResponse(HttpStatusCode.OK);  
  12.    return response;  
  13. }  

SharePointDialog.cs

I have modified GreetWelcome method, which will greet user and provide url for authentication. I have kept this url in web.config as ‘SHAREPOINT_LOGIN_URI’ key. As we are working on development environment, I put localhost web application value. This url is targeted to action ‘LoginWithSharePoint’ of ‘Home’ controller. We will pass username of current user as query string parameter to save token against it after login.

web.config entries (bot application)

  1. <add key="SHAREPOINT_LOGIN_URI" value="https://localhost:44331/HOME/LoginWithSharePoint"/>  
  1. [LuisIntent("Greet.Welcome")]  
  2. public async Task GreetWelcome(IDialogContext context, LuisResult luisResult)  
  3. {  
  4.    StringBuilder response = new StringBuilder();  
  5.   
  6.    if (this.msgReceivedDate.ToString("tt") == "AM")  
  7.    {  
  8.       response.Append($"Good morning, {userName}.. :)");  
  9.    }  
  10.    else  
  11.    {  
  12.       response.Append($"Hey {userName}.. :)");  
  13.    }  
  14.   
  15.    string sharepointLoginUrl = ConfigurationManager.AppSettings["SHAREPOINT_LOGIN_URI"];  
  16.   
  17.    response.Append($"<br>Click <a href='{sharepointLoginUrl}?userName={this.userName}' >here</a> to login");  
  18.   
  19.    await context.PostAsync(response.ToString());  
  20.    context.Wait(this.MessageReceived);  
  21. }

 

SharePoint

3. When user clicks on link, control will go to LoginWithSharePoint action method in Home controller of our MVC web app. We will get user name from query string parameter. We will save it to session for future use.

 

4. We will form O365 authentication url using SharePoint site url, client id of app and redirect uri. Navigate the user to login page. I have provided redirect URI as action method LoggedinToSharePoint of Home controller.

web.config entries (AuthenticationWebApp)

  1. <add key="SPAUTH_APPCLIENTID" value=""/>  
  2. <add key="SPAUTH_SITEURI" value=""/>  
  3. <add key="SPAUTH_REDIRECTURI" value="https://localhost:44331/HOME/LoggedinToSharePoint"/>  
  1. public ActionResult LoginWithSharePoint(string userName)  
  2. {  
  3.    /// Save User Id to session  
  4.    Session["SkypeUserID"] = userName;  
  5.   
  6.    string spAuth_SiteUri = Convert.ToString(ConfigurationManager.AppSettings["SPAUTH_SITEURI"]);  
  7.   
  8.    string spAuth_AppClientId = Convert.ToString(ConfigurationManager.AppSettings["SPAUTH_APPCLIENTID"]);  
  9.   
  10.    string spAuth_RedirectUri = Convert.ToString(ConfigurationManager.AppSettings["SPAUTH_REDIRECTURI"]);  
  11.   
  12.    string url = $"{spAuth_SiteUri}/_layouts/15/appredirect.aspx?client_id={spAuth_AppClientId}&redirect_uri={spAuth_RedirectUri}";  
  13.   
  14.    /// Redirect to login page  
  15.    return Redirect(url);  
  16. }

5. After successful login, ACS will return control to Redirect URI i.e. in LoggedinToSharePoint action method. ACS will make post call to reditect URI and send ContextToken as Form parameter named SPAppToken.

6. Our application will save ContextToken against user name in MongoDB and ask user to continue with chat by returning View. 

  1. public ActionResult LoggedinToSharePoint()  
  2. {  
  3.    string contextToken = this.Request.Form["SPAppToken"];  
  4.    string userName = Convert.ToString(Session["SkypeUserID"]);  
  5.    new Mongo().Insert("ContextTokens"new Token(userName, contextToken));  
  6.   
  7.    return View();  
  8. }  

Contracts.cs

  1. public class Token  
  2. {  
  3.    public ObjectId _id;  
  4.    public string UserName;  
  5.    public string ContextToken;  
  6.   
  7.    public Token(string userName, string contextToken)  
  8.    {  
  9.       UserName = userName;  
  10.       ContextToken = contextToken;  
  11.    }  
  12. } 
Mongo.cs

  1. public class Mongo  
  2. {  
  3.    private IMongoDatabase _database;  
  4.   
  5.    public Mongo()  
  6.    {  
  7.       string _connectionString = ConfigurationManager.AppSettings["MONGO_CONNECTIONSTRING"];  
  8.   
  9.       MongoUrl mongoUrl = MongoUrl.Create(_connectionString);  
  10.   
  11.       MongoClient _client = new MongoClient(new MongoClientSettings  
  12.       {  
  13.          Server = new MongoServerAddress(mongoUrl.Server.Host, mongoUrl.Server.Port)  
  14.       });  
  15.   
  16.       _database = _client.GetDatabase(MongoUrl.Create(_connectionString).DatabaseName, null);  
  17.   
  18.    }  
  19.   
  20.    public void Insert<T>(string collectionName, T document)  
  21.    {  
  22.       IMongoCollection<T> collection = _database.GetCollection<T>(collectionName);  
  23.   
  24.       collection.InsertOne(document);  
  25.    }  
  26.   
  27.    public T Get<T>(string collectionName, string property, string value)  
  28.    {  
  29.       IMongoCollection<T> collection = _database.GetCollection<T>(collectionName);  
  30.   
  31.       var filter = Builders<T>.Filter.Eq<string>(property, value);  
  32.   
  33.       return collection.Find(filter).SingleOrDefault();  
  34.    }
  35. }  

You can see context tokens are saved in MongoDB using RoboMongo (client app for MongoDB)

7. After successful login user comes back to chat window and starts a conversation with bot. Let’s say, user will search for Amit. LUIS will identify intent and control will go to SearchPeople method of SharePointDialog. Here it will extract the entity as Amit and invoke FindUserByName method of SharePoint repository.

  1. public async Task SearchPeople(IDialogContext context, LuisResult luisResult)  
  2. {  
  3.    EntityRecommendation employeeName;  
  4.   
  5.    string searchTerm_PersonName = string.Empty;  
  6.   
  7.    if (luisResult.TryFindEntity("Person.Name"out employeeName))  
  8.    {  
  9.       searchTerm_PersonName = employeeName.Entity;  
  10.    }  
  11.   
  12.    if (string.IsNullOrWhiteSpace(searchTerm_PersonName))  
  13.    {  
  14.       await context.PostAsync($"Unable to get search term.");  
  15.    }  
  16.    else  
  17.    {  
  18.       await context.PostAsync(new SharePoint(this.userName).FindUsersByName(searchTerm_PersonName));  
  19.    }  
  20.   
  21.    context.Wait(this.MessageReceived);  
  22. }  

8. In FindUsersByName( ) method, Token for respective user is retrieved from MongoDB. And it will be used to create clientcontext. I have PeopleDetails list in SharePoint site with following details. Then CAML CONTAINS query will be executed against PeopleDetails list for Title column.

  1. public string FindUsersByName(string searchTermName)  
  2. {  
  3.    string users = string.Empty;  
  4.   
  5.    Token token = new Mongo().Get<Token>("ContextTokens""UserName"this._userName);  
  6.   
  7.    using (ClientContext context = TokenHelper.GetClientContextWithContextToken(_siteUri, token.ContextToken, "localhost:44331"))  
  8.    {  
  9.       CamlQuery query = new CamlQuery();  
  10.   
  11.       query.ViewXml = $"<View><Query><Where><Contains><FieldRef Name='Title' /><Value Type='Text'>{searchTermName}</Value></Contains></Where></Query></View>";  
  12.   
  13.    ListItemCollection peopleDetails = context.Web.Lists.GetByTitle("PeopleDetails").GetItems(query);  
  14.   
  15.    context.Load(peopleDetails);  
  16.   
  17.    context.ExecuteQuery();  
  18.   
  19.    users = string.Join("<br>", peopleDetails.Select(x => x["Title"] + "(" + x["ContactNumber"] + "),"));  
  20.    }  
  21.   
  22.    return users;  
  23. }  

9. Chat bot will return html containing list of users and their contact numbers. Keep trying different authentication services. Happy Chatting! :)

Next Recommended Readings