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
Related
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.
I have the following C# code:
using (SPSite site = new SPSite("http://mysharepointsiteurl")
{
using (SPWeb web = site.OpenWeb())
{
SPListItemCollection itemCollection = web.Lists["List Name"].Items;
foreach (SPListItem item in itemCollection)
{
Console.WriteLine(item["Field Name"]);
// prints 5 different results.
}
web.Dispose();
}
site.Dispose();
Is there anyway I can get, say the 4th printed out result, and store it in a string? I'm sure there is a way but I can't seem to work it out. Thanks for any help! :)
You can use the indexer to get the item at a given position:
using (SPSite site = new SPSite("http://mysharepointsiteurl"))
using (SPWeb web = site.OpenWeb())
{
var items = web.Lists["List Name"].GetItems("Field Name");
string value = (string)items[3]["Field Name"];
}
right now, I'm using the SPSecurity.RunWithElevatedPrivileges method to let anonymous users add list items to a list. What i would like to do is make a general method that takes a Site, List and List item as an argument and adds the item to the list being passed. Right now I have :
public static void AddItemElevated(Guid siteID, SPListItem item, SPList list)
{
SPSite mySite = SPContext.Current.Site;
SPList myList = WPToolKit.GetSPList(mySite, listPath);
SPWeb myWeb = myList.ParentWeb;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite eleSite = new SPSite(mySite.ID))
{
using (SPWeb eleWeb = eleSite.OpenWeb(myWeb.ID))
{
eleWeb.AllowUnsafeUpdates = true;
SPList eleList = eleWeb.Lists[myList.Title];
SPListItem itemToAdd = list.Items.Add();
itemToAdd = item;
itemToAdd.Update();
eleWeb.AllowUnsafeUpdates = false;
}
}
});
}
The problem is that 'item' gets initialized outside of the elevated privileges so when 'itemToAdd' is set to 'item' it loses its elevated privileges, causing the code to break at 'item.update()' if used my an non-privileged user.
Any Thoughts?
The problem could be because you are passing in your list. Try just passing in the list name and then grabbing the list from the elevated web like this:
public static void AddItemElevated(SPListItem itemToAdd, string listName)
{
SPWeb web = SPContext.Current.Web;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite elevatedSite = new SPSite(web.Url))
{
using (SPWeb elevatedWeb = elevatedSite.OpenWeb())
{
elevatedWeb.AllowUnsafeUpdates = true;
SPList list = elevatedWeb.Lists[listName];
SPListItem item = list.Items.Add();
item = itemToAdd;
item.Update();
elevatedWeb.AllowUnsafeUpdates = false;
}
}
}
}
Following line itemToAdd = item; does something strange - you adding item to one list (with list.Items.Add() ) but updating item from another list/location (one that comes as argument).
Not sure what you actually want, but maybe you want to co copy all fileds from item to itemToAdd. Consider in this case to pass fieldName/value pairs as argument to make it clear that you are adding new item with given values.
Note, that anonymous users are able to add items to lists that explicitly allow it.
I haven't tried it but possibly this could help - http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.splistitem.copyto.aspx
Regards,
Nitin Rastogi
If item is coming from an SPList.AddItem() method, the splist instance must be get from an elevated web. otherwise this code will always break for anonymous users.
or you can allow anonymous user to add item to list, so you won't need running the code with elevated privileges.
by the way, itemToAdd = item; is not a correct way of setting the new added item to an old instance.
I have an Image List on each and every web (SPWeb) of a SiteCollection. I want to set a specific property of this List. I am iterating through all the Sites withing a SiteCollection and finding the List and setting its properties. My problem is that I can set the properties of a List present at first level Sites, but can't set the properties of Lists, present at 2nd or 3rd level Sites. For example,
Here is site hierarchy:
Home (Rootweb) 1st level
Home-> Aboutus (subsite) 2nd level
Home->Aboutus->Our Mission (subsite) 3rd level
here is the code for that!
using (SPSite oSPsite = new SPSite(http://spdev/))
{
foreach (SPWeb web in oSPsite.AllWebs)
{
SPList list = web.GetList("PublishingImages");
if (list != null)
{
foreach (SPContentType contentType in list.ContentTypes)
{
if (contentType.Name == "Publishing Picture")// but id is better
{
list.EnableModeration = false;
list.Update();
}
}
}
web.Dispose();
}
}
Is it because I'm disposing the parent first?
Assuming the list name is the same on every site (PublishingImages) and you're on WSS 3.0 or MOSS07 here is the sample code:
using (SPSite oSPsite = new SPSite("yourSiteUrlHere"))
{
SPWebCollection siteWebs = oSPsite.AllWebs;
foreach (SPWeb web in siteWebs)
{
try
{
SPList list = null;
try
{
list = web.Lists["PublishingImages"];
}
catch {}
if (list != null)
{
// todo: update list properties here
list.Update();
}
}
finally
{
if(web != null)
web.Dispose();
}
}
}
As Ashutosh mentioned, there are some properties that don't work on all list types but I'm assuming since you've already stated it works on some of them you aren't setting any of those.
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);
}
}