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.
Related
I am trying to access the lists in a SharePoint site, I am using Sharepoint 365 with the modern experience.
My problem is that I get timeout error on the line
clientContext.ExecuteQuery();
I used this link as reference :
https://learn.microsoft.com/en-us/sharepoint/dev/sp-add-ins/complete-basic-operations-using-sharepoint-client-library-code#basic-operations-with-the-sharepoint-net-client-object-model
This is my code:
using (ClientContext clientContext = new ClientContext("https:siteurl"))
{
SecureString passWord = new SecureString();
foreach (char c in "mypwd".ToCharArray()) passWord.AppendChar(c);
clientContext.Credentials = new SharePointOnlineCredentials("myuser", passWord);
Web web = clientContext.Web;
// Retrieve all lists from the server.
// For each list, retrieve Title and Id.
clientContext.Load(web.Lists,
lists => lists.Include(list => list.Title,
list => list.Id));
// Execute query.
clientContext.ExecuteQuery();
// Enumerate the web.Lists.
foreach (List list in web.Lists)
{
label1.Text = label1.Text + ", " + list.Title;
}
}
I have a file list inside desktop app thats fetched from the sharepoint online document library. What i want to do is to provide a posibility to show that file in the browser. But i'm not able to generate proper url.
Here is a csom code snippet to get file url in a document library:
using (ClientContext ctx = new ClientContext("https://zheguo.sharepoint.com/sites/dev/"))
{
ctx.Credentials = new SharePointOnlineCredentials(account, secret);
ctx.Load(ctx.Web);
ctx.ExecuteQuery();
List targetList = ctx.Web.Lists.GetByTitle("Documents");
ListItemCollection ItemCol = targetList.GetItems(CamlQuery.CreateAllItemsQuery());
ctx.Load(ItemCol);
ctx.ExecuteQuery();
foreach (Microsoft.SharePoint.Client.ListItem item in ItemCol)
{
if (item.FileSystemObjectType == FileSystemObjectType.File)
{
Console.WriteLine(new Uri(ctx.Url).GetLeftPart(UriPartial.Authority) + item["FileRef"]);
}
}
}
Reference:
Getting the Absolute URL of a File in CSOM
I have Sharepoint enterprise server with list that have "Everyone" user grant as contributor
but, when I execute below code with authenticated user (let say, user Abc), for add item list row, the row never added to list
SPWeb web1 = SPContext.Current.Web;
using (SPSite site = new SPSite(web1.Url))
{
using (SPWeb web = site.OpenWeb())
{
SPList roomList = web.Lists.TryGetList(LIST_NAME);
if (roomList != null)
{
SPListItem newItem = roomList.Items.Add();
PopulateListWithData(data, ref newItem);
newItem.Update();
}
}
}
}
How can I add row to list with user Abc?
try to add using following code
using (SPSite site = new SPSite(SPContext.Current.Site.Url))
{
using (SPWeb web = site.OpenWeb(SPContext.Current.Web))
{
SPList roomList = web.Lists.TryGetList(LIST_NAME);
if (roomList != null)
{
SPListItem newItem = roomList.AddItem();
PopulateListWithData(data, ref newItem);
newItem.Update();
}
}
}
if you still have the same issue
try to ensure the following
list you try to add to already exists in root web site
List name is types right because your code may be break after TryGetList
after that if still have the same issue you need to debug or check sharepoint logs to catch exception that happen
How i can query sharepoint list items using soap in c#?
Code that should query data will be placed on one host (sharepoint 2007, .net 2.0). List located on another host (Sharepoint 2010).
As far as I know, I can not use for this purpose SPSite, SPWeb..
using(SPSite site = new SPSite("http://hostname/...")) {
using(SPWeb web = site.OpenWeb()) {
...
Can anyone give me an example of how this can be done?
Tnx!
To integrate between two different sharepoint instances you have to use the sharepoint web services.
In your project create a web reference to the following url: http://sharepointserver/_vti_bin/lists.asmx
Create a connection to the web service:
var client = new SharePointWebServices.Lists { Credentials = new NetworkCredential("username", "password") };
var xmlDoc = new XmlDocument();
var viewFields = xmlDoc.CreateElement("ViewFields");
viewFields.InnerXml = "<FieldRef Name=\"ows_FIELD YOU WISH TO RETRIEVE\" />";
var listGuid = ConfigurationManager.AppSettings["GUID_OF_LIST"];
XmlNode listItems = client.GetListItems(listGuid, null, null, viewFields,
null, null, null);
Now you have received your collection. simply iterate through the xmlDoc retrieved from the webservice. I do this like this:
foreach (XmlNode node in listItems)
{
if (node.Name == "rs:data")
{
for (int f = 0; f < node.ChildNodes.Count; f++)
{
if (node.ChildNodes[f].Name == "z:row")
{
var xmlAttributeCollection = node.ChildNodes[f].Attributes;
if (xmlAttributeCollection != null)
{
string listItem = xmlAttributeCollection["ows_ows_FIELD YOU WISH TO RETRIEVE"].Value;
}
}
}
}
}
You can use SharePoint soap web services. Or if you are getting data from SharePoint 2010 you can use
its rest api.
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);
}
}