Sharepoint List in Provider Hosted App
This Blog will provide an insight of how we can use Sharepoint List and its properties in Provider Hosted App. Assuming you already are familiar with Sharepoint and Provider Hosted App.
As we all know Provider Hosted App runs outside the Sharepoint farm, it can also be on a totally different server. So, the point rises how one can have access to Sharepoint lists to perform actions. The answer is not as difficult as it might seem.
When you create a new project for Provider Hosted App, you get two inbuilt classes:
- SharepointContext.cs
- TokenHelper.cs
These are the files that help your App to communicate with the Sharepoint. To get access to lists, web and all other properties of Sharepoint you will need to create a client context token using the methods provided to you by these classes.
Code Example of creating your client context:
private void GetContextToken()
{
// The following code gets the client context and Title property by using TokenHelper.
// To access other properties, the app may need to request permissions on the host web.
var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);
using (var clientContext = spContext.CreateUserClientContextForSPHost())
{
Session["clientContext"] = clientContext;
//Get the site name.
clientContext.Load(clientContext.Web, web => web.Title);
clientContext.ExecuteQuery();
siteName = clientContext.Web.Title;
//Get the current user.
clientContext.Load(clientContext.Web.CurrentUser, currentUser => currentUser.LoginName);
clientContext.ExecuteQuery();
loginName = clientContext.Web.CurrentUser.LoginName;
}
string contextTokenString = TokenHelper.GetContextTokenFromRequest(Request);
if (contextTokenString != null)
{
contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, Request.Url.Authority);
sharepointUrl = new Uri(Request.QueryString["SPHostUrl"]);
accessToken = TokenHelper.GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
}
else if (!IsPostBack)
{
Response.Write("Could not find a context token.");
return;
}
}
This chunk of code will help you create the context token that will be used to get the properties of Sharepoint.
Now, to get a list named "Projects" in your Sharepoint farm within your app:
projectList = clientContext.Web.Lists.GetByTitle("Projects");
where, projectList is a Microsoft.Sharepoint.Client.List
To get the items from the Projects List we use CAML query.
CamlQuery query = CamlQuery.CreateAllItemsQuery(100);
Microsoft.SharePoint.Client.ListItemCollection itemsProject = projectList.GetItems(query);
clientContext.Load(itemsProject);
clientContext.ExecuteQuery();
itemsProject is a Sharepoint ListItemCollection that contains top 100 items form Projects List.
Now, Suppose we need to get items based on some criteria. For example we need to get all Tasks that come within a project. For this, first we will have the Tasks List from Sharepoint and then perform a CAML query based on our criteria:
query = new CamlQuery();
lstTasks = clientContext.Web.Lists.GetByTitle("Tasks");
query.ViewXml = "<View><Query><Where><Eq><FieldRef Name='ProjectID' /><Value Type='Number'>" + projectID + "</Value></Eq></Where></Query></View>";
Microsoft.SharePoint.Client.ListItemCollection tasksItems = lstTasks.GetItems(query);
clientContext.Load(tasksItems);
clientContext.ExecuteQuery();
If you will observe the above code chunk you will notice everything was similar to the above code but the line that made the difference is how CAML query was written. In the above example we simple used CreateAllItemsQuery Method to get all items. But in this example we created our own XML query for filtering the items as per our need.
There are number of operators that you can use to create your query for example:
For Equals - 'eq'
For GreaterThanEqualTo - 'Geq'
For LessThanEqualTo - 'Leq'
etc.....
"FieldRef Name" contains the Name of the column we need to apply filter on. "Value Type" defines its Type.
To ADD/EDIT/DELETE Items in Sharepoint List:
Add:
ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
projectList = clientContext.Web.Lists.GetByTitle("Projects");
Microsoft.SharePoint.Client.ListItem lstItem;
lstItem = projectList.AddItem(itemCreateInfo);
lstItem["Title"] = "Test Project";
lstItem["ProjectAddress"] = "Evon Technologies";
lstItem["ProjectLocation"] = "DehraDun";
lstItem["StartDate"] = //Date Format;
lstItem["CompletionDate"] = //Date Format;
lstItem.Update();
clientContext.ExecuteQuery();
Edit
ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
projectList = clientContext.Web.Lists.GetByTitle("Projects");
Microsoft.SharePoint.Client.ListItem lstItem;
lstItem = projectList.GetItemById(ProjectID);
lstItem["Title"] = "Test Project";
lstItem["ProjectAddress"] = "Evon Technologies";
lstItem["ProjectLocation"] = "DehraDun";
lstItem["StartDate"] = //Date Format;
lstItem["CompletionDate"] = //Date Format;
lstItem.Update();
clientContext.ExecuteQuery();
If your Sharepoint List have a "FieldLookUp" column, it can be added or edited as:
lstItem["Manager"] = new List<FieldLookupValue> { new FieldLookupValue() { LookupId = 1} };
Delete
projectList = clientContext.Web.Lists.GetByTitle("Projects");
Microsoft.SharePoint.Client.ListItem listItem = projectList.GetItemById(ProjectID);
listItem.DeleteObject();
clientContext.ExecuteQuery();
Now feel free and play around Sharepoint Lists in your own Provider Hosted App.
Happy Coding...
0 Comment(s)