Retrieve items from a SharePoint list - c#

I have searched this question on the web but to no result that fits my problem.
I am trying to retrive a specific colum in a sharepoint online list and comparing it to the currently logged in user. this is my code so far.
var spContext = SharePointContextProvider.Current.GetSharePointContext((HttpContext));
using (var clientContext = spContext.CreateUserClientContextForSPHost())
{
if (clientContext != null)
{
var user = GetUser(clientContext);
var items = LoadList(clientContext);
foreach (ListItem listItem in items)
{
if (user.Title == listItem["Author"].ToString())
{
//Do stuff later
}
}
}
}
public ListItemCollection LoadList(ClientContext context)
{
List announcementsList = context.Web.Lists.GetByTitle("Arbetsplan");
CamlQuery query = CamlQuery.CreateAllItemsQuery();
ListItemCollection items = announcementsList.GetItems(query);
context.Load(items);
context.ExecuteQuery();
return items;
}
public User GetUser(ClientContext context)
{
var user = context.Web.CurrentUser;
context.Load(user);
context.ExecuteQuery();
return user;
}
The error I get is like this:
The
Author column is of type
Person or Group. I have an idea that that's where the problem is. I am not handling the type correctly?
The Author field in the SharePoint list is named "Created By". But to reach it I have to use the intrenal name.

Related

How can I Read a list from a sharepoint site and make the contents globaly available in my code?

My code works, when I redundantly put it in objects like button_click or comboBoxApp_SelectedIndexChanged, but when I try to put it in a centralized location i get "The name 'items' does not exist in the current context"
''' ClientContext context = new ClientContext("https://MySharePointSite/ServerMaintenance/");
List ChangeList = context.Web.Lists.GetByTitle("Server Maintenance Windows");
CamlQuery query = CamlQuery.CreateAllItemsQuery(1505);
ListItemCollection items = ChangeList.GetItems(query);
context.Load(items);
context.ExecuteQuery();'''
Create a static method to return ListItemCollection object and then you can call this function anywhere you want, here is the code snippet for your reference:
static void Main(string[] args)
{
ListItemCollection items = GetItems();
foreach (ListItem item in items)
{
Console.WriteLine(item["Title"]);
}
}
private static ListItemCollection GetItems()
{
ClientContext context = new ClientContext("http://sp/sites/Jerry");
List ChangeList = context.Web.Lists.GetByTitle("TestList");
CamlQuery query = CamlQuery.CreateAllItemsQuery(1505);
ListItemCollection items = ChangeList.GetItems(query);
context.Load(items);
context.ExecuteQuery();
return items;
}

How to notify user when programatically adding them to a group

I am adding members to a group with the code below.
My question is very simple :
When adding members with this code, the invited person does not get an email notifying them. However when doing the same from the UI there is an option to notify the user. How can I do that from the code?
public void UpdateGoupMembers(string groupName, List<string> loginNames)
{
using (var clientContext = new ClientContext(baseUrl))
{
clientContext.Credentials = credentials;
var web = clientContext.Web;
var group = web.SiteGroups.GetByName(groupName);
if (group != null)
{
foreach (var loginName in loginNames)
{
var user = web.EnsureUser(loginName);
if (user != null)
{
group.Users.AddUser(user);
}
}
var existingUsers = group.Users;
clientContext.Load(existingUsers, includes => includes.Include(
f => f.LoginName,
f => f.UserId,
f => f.PrincipalType,
f => f.Email,
f => f.Id));
clientContext.ExecuteQuery();
foreach (var existingUser in existingUsers)
{
var userName = existingUser.LoginName.Split('|')[2];
if (!loginNames.Contains(userName))
{
group.Users.RemoveByLoginName(existingUser.LoginName);
}
}
}
clientContext.ExecuteQuery();
}
}
I do not believe it is possible to send a Welcome Email when users are added to a group programatically based off of the method documentation.
However, you can use the CSOM library to send an email programatically to the specific user after adding them to the group. Send Emails via SharePoint CSOM will be a great reference on how to do this.

Code to list all permissions for SharePoint Folders

I'm after some C# code to recursively enumerate all the folders in a SharePoint web site and list the permissions applying to them to be run from a Sharepoint client machine. Can anyone provide or point me to an example?
The following code can perform this function on a server using SPSite object ( from https://social.msdn.microsoft.com/Forums/sqlserver/en-US/8c7c5735-039e-4cb9-a2b5-58d70a10793f/get-permissions-group-from-folders-tree-view-on-a-doc-library?forum=sharepointdevelopmentprevious) but I need to run it using SharePoint Client code
public static void getPermissionsOfFolders()
{
using (SPSite site = new SPSite("http://sp"))
{
using (SPWeb web = site.RootWeb)
{
SPList list = web.GetList("/Lists/List2");
foreach (SPListItem item in list.Folders)
{
Console.WriteLine("ID: "+item["ID"]+"--"+item.SortType);
if (SPFileSystemObjectType.Folder == item.SortType)
{
SPRoleAssignmentCollection roles = item.RoleAssignments;
foreach (SPRoleAssignment role in roles)
{
Console.WriteLine("~");
Console.WriteLine("Name: "+role.Member.Name);
SPRoleDefinitionBindingCollection bindings = role.RoleDefinitionBindings;
XmlDocument doc = new XmlDocument();
doc.LoadXml(bindings.Xml);
XmlNodeList itemList = doc.DocumentElement.SelectNodes("Role");
foreach (XmlNode currNode in itemList)
{
string s = currNode.Attributes["Name"].Value.ToString();
Console.WriteLine("Permission Level: "+s);
}
}
Console.WriteLine("--------------------------------------");
}
}
}
}
}
Code below fails with exception "Property ListItemAllFields not found" as shown below on clientContext.ExecuteQuery()
private void ListSPPermissions3()
{
string sSite = "http://server2012a/sites/TestDocs/";
using (var clientContext = new ClientContext(sSite))
{
Site site = clientContext.Site;
Web web = clientContext.Web;
List list = web.Lists.GetByTitle("Shared Documents");
clientContext.Load(list.RootFolder.Folders); //load the client object list.RootFolder.Folders
clientContext.ExecuteQuery();
int FolderCount = list.RootFolder.Folders.Count;
foreach (Microsoft.SharePoint.Client.Folder folder in list.RootFolder.Folders)
{
RoleAssignmentCollection roleAssCol = folder.ListItemAllFields.RoleAssignments;
clientContext.Load(roleAssCol);
clientContext.ExecuteQuery(); // Exception property ListItemAllFields not found
foreach (RoleAssignment roleAss in roleAssCol)
{
Console.WriteLine(roleAss.Member.Title);
}
}
}
}
There are at least the following flaws with your example:
The specified example only allows to retrieve folders one level
beneath:
clientContext.Load(list.RootFolder.Folders); //load the client object list.RootFolder.Folders
clientContext.ExecuteQuery();
Role assignments could be retrieved using a single request to the
server (see the below example), hence there is no need to perform
multiple requests to retrieve role assignments per folder.
Folder.ListItemAllFields property is supported only in SharePoint
2013 CSOM API
Having said that i would recommend to consider the following example to enumerate folder permissions:
using (var ctx = new ClientContext(webUri))
{
var list = ctx.Web.Lists.GetByTitle(listTitle);
var items = list.GetItems(CamlQuery.CreateAllFoldersQuery());
ctx.Load(items, icol => icol.Include(i => i.RoleAssignments.Include( ra => ra.Member), i => i.DisplayName ));
ctx.ExecuteQuery();
foreach (var item in items)
{
Console.WriteLine("{0} folder permissions",item.DisplayName);
foreach (var assignment in item.RoleAssignments)
{
Console.WriteLine(assignment.Member.Title);
}
}
}
The error is probably because the SharePoint SDK you are using is pre-SharePoint 2013 CSOM.
Folder.ListItemAllFields
property is available in SharePoint 2013 CSOM
For SharePoint 2010, you have to access folders like list items
ListItem item = context.Web.Lists.GetByTitle("Shared Documents").GetItemById(<item ID>);
and then get the RoleAssignments for the items.

Sharepoint Client Object Model Updating Property of a only one folder

I am working on a sharepoint clientobjectmodel code.
There is a folder called "John Details" inside "User Details Folder".
I am trying to update 2 properties for the "John Details" folder.
How do I do that?
Public Void UpdateColumnsForOnlyOneFolder(maildId1,mailId2){
ClientContext ctx = new ClientContext("http://mytestsite/");
List list = ctx.Web.Lists.GetByTitle("User Details");
Microsoft.SharePoint.Client.ListItemCollection items = list.GetItems(CamlQuery.CreateAllItemsQuery());
ctx.Load(items);
ctx.ExecuteQuery();
foreach (var item in items)
{
item["email1"] = mailId1;
item["email2"] = mailId2;
item.Update();
}
ctx.ExecuteQuery();
}
If I understood your question properly, you would like to update the folder's associated list item properties. If so, you could consider the following approach:
Get Folder by url using Web.GetFolderByServerRelativeUrl method
Get associated List Item using Folder.ListItemAllFields property
Update List Item properties
Example
using (var ctx = new ClientContext(webUri))
{
var web = ctx.Web;
var folder = web.GetFolderByServerRelativeUrl("/site/Documents/folder/sub folder");
var listItem = folder.ListItemAllFields;
listItem["PropertyName"] = "PropertyValue";
listItem.Update();
ctx.ExecuteQuery();
}
Here is the code that will update only the items of one folder
Public Void UpdateColumnsForOnlyOneFolder(maildId1,mailId2){
ClientContext ctx = new ClientContext("http://mytestsite/");
List list = ctx.Web.Lists.GetByTitle("User Details");
CamlQuery spQuery = CamlQuery.CreateAllItemsQuery();
spQuery.FolderServerRelativeUrl = "Enter Relative URL TO FOLDER" // Example "/managedpath/site/Lists/listname/Folder Name"
Microsoft.SharePoint.Client.ListItemCollection items = list.GetItems(spQuery);
ctx.Load(items);
ctx.ExecuteQuery();
foreach (Microsoft.SharePoint.Client.ListItem item in items)
{
item["email1"] = mailId1;
item["email2"] = mailId2;
item.Update();
}
ctx.ExecuteQuery();
}
Please mark as answer , if this works for you.

Retrieve list items from sharepoint

I am trying to retrieve some Items from a sharepoint 2013 online list. I know for sure that there are 3 Items in the list. Somehow the code does not return any Items. Does anybody know why not? In debugging listItems is empty.
User spUser = null;
SharePointContextToken contextToken;
string accessToken;
Uri sharepointUrl;
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;
var clientContext = TokenHelper.GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
Web web = clientContext.Web;
List list = clientContext.Web.Lists.GetByTitle("CustomListFacturen");
clientContext.Load(list);
CamlQuery query = new CamlQuery();
query.ViewXml = "<View><RowLimit>100</RowLimit></View>";
ListItemCollection listItems = list.GetItems(query);
clientContext.Load(listItems);
clientContext.ExecuteQuery();
if (listItems.Any())
{
ViewBag.Message = "Items are found!!!";
}
}
I didn't try and run your code, but it looks almost exactly like this code, basic CSOM list operations.
You don't need that first .Load(list) and you could try using the CamlQuery.CreateAllItemsQuery(100) instead of the CAML.
Your app does not have enough permissions.

Categories