Sharepoint Client Object Model Updating Property of a only one folder - c#

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.

Related

Retrieve items from a SharePoint list

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.

Unable to gain access to Name for Files within a Site Share Point

I have method where I am adding new files to a Site. I am trying to implement a method where I can delete a file from a Site. Currently the method is deleting the files from oldest to newest. Where I would like to have access to Name or DisplayName to perform a if check. When I try to access listitem.DisplayName I am met with en error of:
"The property or field 'DisplayName' has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested."
If someone can please help me understand how to allow listitem.DisplayName to be accessible I would greatly appreciate it!
DeleteAFile()
public static void DeleteAFile(string sFileName, string sFldrLoc)
{
ClientContext clientContext = new ClientContext(siteURL);
List spList = clientContext.Web.Lists.GetByTitle(sFldrLoc);
CamlQuery query = new CamlQuery();
ListItemCollection listItems = spList.GetItems(query);
clientContext.Load(listItems);
clientContext.ExecuteQuery();
foreach (ListItem listitem in listItems)
{
Console.WriteLine(listitem.DisplayName); // Line that is throwing error
// listitem.DeleteObject();
clientContext.ExecuteQuery();
}
}
Solved
Thank you to Thriggle for the link which helped me solved this. Updated code below:
DeleteAFile()
/// <summary>
/// Will list out all the items within a Site, conduct a search and delete the item when found.
/// </summary>
/// <param name="sFileName"></param>
/// <param name="sFldrLoc"></param>
public static void DeleteAFile(string sFileName, string sFldrLoc)
{
ClientContext clientContext = new ClientContext(siteURL);
Web web = clientContext.Web;
ListCollection collList = web.Lists;
List oList = collList.GetByTitle(sFldrLoc);
CamlQuery query = new CamlQuery();
query.ViewXml = "<View><Query><Where><Leq>" +
"<FieldRef Name='ID'/><Value Type='Number'>100</Value>" +
"</Leq></Where></Query><RowLimit>50</RowLimit></View>";
ListItemCollection collListItem = oList.GetItems(query);
clientContext.Load(collListItem,
items => items.IncludeWithDefaultProperties(
item => item.DisplayName));
clientContext.ExecuteQuery();
foreach (ListItem listitem in collListItem)
{
if (listitem.DisplayName.Equals(sFileName))
{
listitem.DeleteObject();
clientContext.ExecuteQuery();
Console.WriteLine("{0}, has been deleted sucessfully!", listitem.DisplayName);
}
}
}
You can update your invocation of clientContext.Load to indicate which properties to retrieve for each list item.
clientContext.Load(listItems,
items => items.IncludeWithDefaultProperties(
item => item.DisplayName));
For reference, see How to retrieve list items.

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.

How to get list of Folders and subfolders created in "List"?

I am trying to access list of all Sites and Lists from Sharepoint 2007 using c#.
I am able to get Name of sites and list.
But unable to get folders and subfolders of particular list.
And Document uploaded in particular Folder.
I am using Web Services (no dependency of Microsoft.Sharepoint.dll)
Regards,
Jene
Try this:
using(SPSite site = new SPSite("http://yoursite"))
using(SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["your_doclib"];
SPQuery query = new SPQuery()
{
Query = "",
ViewAttributes = #"Scope=""RecursiveAll"""
};
SPListItemCollection itens = list.GetItems(query);
foreach (SPListItem item in itens)
{
Console.ForegroundColor =
item.FileSystemObjectType == SPFileSystemObjectType.Folder ?
ConsoleColor.White : ConsoleColor.Gray;
Console.WriteLine("{0}", item.Name);
}
}

SharePoint : How can I programmatically add items to a custom list instance

I am really looking for either a small code snippet.
I have a C# console app that I will use to somehow add list items to my custom list. I have created a custom content type too. So not sure if I need to create an C# class from this content type too. Perhaps not.
I think these both blog post should help you solving your problem.
http://blog.the-dargans.co.uk/2007/04/programmatically-adding-items-to.html
http://asadewa.wordpress.com/2007/11/19/adding-a-custom-content-type-specific-item-on-a-sharepoint-list/
Short walk through:
Get a instance of the list you want to add the item to.
Add a new item to the list:
SPListItem newItem = list.AddItem();
To bind you new item to a content type you have to set the content type id for the new item:
newItem["ContentTypeId"] = <Id of the content type>;
Set the fields specified within your content type.
Commit your changes:
newItem.Update();
To put it simple you will need to follow the step.
You need to reference the Microsoft.SharePoint.dll to the application.
Assuming the List Name is Test and it has only one Field "Title" here is the code.
using (SPSite oSite=new SPSite("http://mysharepoint"))
{
using (SPWeb oWeb=oSite.RootWeb)
{
SPList oList = oWeb.Lists["Test"];
SPListItem oSPListItem = oList.Items.Add();
oSPListItem["Title"] = "Hello SharePoint";
oSPListItem.Update();
}
}
Note that you need to run this application in the Same server where the SharePoint is installed.
You dont need to create a Custom Class for Custom Content Type
You can create an item in your custom SharePoint list doing something like this:
using (SPSite site = new SPSite("http://sharepoint"))
{
using (SPWeb web = site.RootWeb)
{
SPList list = web.Lists["My List"];
SPListItem listItem = list.AddItem();
listItem["Title"] = "The Title";
listItem["CustomColumn"] = "I am custom";
listItem.Update();
}
}
Using list.AddItem() should save the lists items being enumerated.
This is how it was on the Microsoft site, with me just tweaking the SPSite and SPWeb since these might vary from environment to environment and it helps not to have to hard-code these:
using (SPSite oSiteCollection = new SPSite(SPContext.Current.Site.Url))
{
using (SPWeb oWeb = oSiteCollection.OpenWeb(SPContext.Current.Web))
{
SPList oList = oWeb.Lists["Announcements"];
// You may also use
// SPList oList = oWeb.GetList("/Lists/Announcements");
// to avoid querying all of the sites' lists
SPListItem oListItem = oList.Items.Add();
oListItem["Title"] = "My Item";
oListItem["Created"] = new DateTime(2004, 1, 23);
oListItem["Modified"] = new DateTime(2005, 10, 1);
oListItem["Author"] = 3;
oListItem["Editor"] = 3;
oListItem.Update();
}
}
Source:
SPListItemClass (Microsoft.SharePoint). (2012). Retrieved February 22, 2012, from http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.splistitem.aspx.
I had a similar problem and was able to solve it by following the below approach (similar to other answers but needed credentials too),
1- add Microsoft.SharePointOnline.CSOM by tools->NuGet Package Manager->Manage NuGet Packages for solution->Browse-> select and install
2- Add "using Microsoft.SharePoint.Client; "
then the below code
string siteUrl = "https://yourcompany.sharepoint.com/sites/Yoursite";
SecureString passWord = new SecureString();
var password = "Your password here";
var securePassword = new SecureString();
foreach (char c in password)
{
securePassword.AppendChar(c);
}
ClientContext clientContext = new ClientContext(siteUrl);
clientContext.Credentials = new SharePointOnlineCredentials("Username#domain.nz", securePassword);/*passWord*/
List oList = clientContext.Web.Lists.GetByTitle("The name of your list here");
ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
ListItem oListItem = oList.AddItem(itemCreateInfo);
oListItem["PK"] = "1";
oListItem["Precinct"] = "Mangere";
oListItem["Title"] = "Innovation";
oListItem["Project_x0020_Name"] = "test from C#";
oListItem["Project_x0020_ID"] = "ID_123_from C#";
oListItem["Project_x0020_start_x0020_date"] = "2020-05-01 01:01:01";
oListItem.Update();
clientContext.ExecuteQuery();
Remember that your fields may be different with what you see, for example in my list I see "Project Name", while the actual value is "Project_x0020_ID". How to get these values (i.e. internal filed values)?
A few approaches:
1- Use MS flow and see them
2- https://mstechtalk.com/check-column-internal-name-sharepoint-list/ or https://sharepoint.stackexchange.com/questions/787/finding-the-internal-name-and-display-name-for-a-list-column
3- Use a C# reader and read your sharepoint list
The rest of operations (update/delete):
https://learn.microsoft.com/en-us/previous-versions/office/developer/sharepoint-2010/ee539976(v%3Doffice.14)

Categories