Sharepoint access to list ignore user permission - c#

I created web part (something like wizard) and need change item value in list, but when get list item, they haven't items (logged user haven't access to this list). Can I ignore sharepoint permission, and update this value?
I use LINQ to sharepoint and get context:
using (SystemOcenContextDataContext ctx = new SystemOcenContextDataContext("http://sh2010/sites/270"))
{
// code :)
}
Update:
make test when get list using:
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite ElevatedSite = new SPSite("http://sh2010/sites/270"))
{
using (SPWeb ElevatedWeb = ElevatedSite.OpenWeb())
{
list = ElevatedWeb.Lists["Ankiety i oceny"];
}
}
});
the object list "have" items
but in my project I use sharepoint linq datacontext when using:
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SystemOcenContextDataContext ctx = new SystemOcenContextDataContext("http://sh2010/sites/270"))
{
item = ctx.AnkietyIOceny.First();
}
});
the context(ctx) didn't have any items :/
any idea?

SPSecurity.RunWithElevatedPrivileges(delegate()
{
// Pur your code here.
});
Get more details Here

The SharePoint linq provides doesn't work with ElevatedPrivileges. It accesses the SPWeb.Current instance which will have the access rights of the request and not the elevated user.
http://jcapka.blogspot.com/2010/05/making-linq-to-sharepoint-work-for.html
There's a work around, which I've implemented generally the same thing. It's a big awkward but it works as far as I can tell.

Related

Sharepoint 365 allowing me to only write two items then stops responding

Background; it was working with SP2013, but a supplier has switched to SP365.
Modifying the authentication using OfficeDevPnP.Core.AuthenticationManager, ClientID and ClientSecret I can get the access token. I can then do all the JSON reads I like, but it will only allow me to write two items to a list (orders), then it just times out. I restart the project and it does exactly the same. I can read the list to make sure the order hasn't been uploaded already, but when it comes to writing the third item it just throws timeout errors.
I updated the code to call for a new access token for each write and just get "Token Request Failed" after the second write.
Any thoughts on how to approach the supplier on config options, or change my approach?
Thanks in advance.
Found the answer, changing up the usage of GetAppOnlyAuthenticatedContext to something like this works wonders.
public void CreateListItemV2(string listName, QDS_WorkOrderEntry entry)
{
OfficeDevPnP.Core.AuthenticationManager authMgr = new OfficeDevPnP.Core.AuthenticationManager();
using (var context = authMgr.GetAppOnlyAuthenticatedContext(SPSiteUrl, "<clientid>", "<secret>"))
{
List list = context.Web.Lists.GetByTitle(listName);
var itemCreateInfo = new ListItemCreationInformation();
var newItem = list.AddItem(itemCreateInfo);
newItem["HHSDetails"] = entry.HHSDetails?.HHSDetailsId;
...
newItem.Update();
context.Load(newItem);
context.ExecuteQuery();
}
}

CSOM Retrieving ListItemCollection is empty

I have tried to make a simple console application that retrieves list items from Share Point Online. It works fine when I retrieve list of the sites or list titles from the site, but I receive no list items when I try to get it from the particular list.
I've listed many examples of similar tasks and almost all of them were written in the same way. That's why I don't exclude that the reason of my case might be in an insufficient permissions (I attach a screenshot of the API permissions).
Please, check my code and permissions. Any help will be highly appreciated.
Application code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security;
using System.Threading.Tasks;
using Microsoft.SharePoint.Client;
using SP = Microsoft.SharePoint.Client;
namespace SharePointTrigger
{
class Program
{
static async Task Main(string[] args)
{
Uri site = new Uri("https://MyCompany.sharepoint.com/sites/MyProject");
string user = $"ServiceUser#MyCompany.com";
string rawPassword = $"password";
SecureString password = new SecureString();
foreach (char c in rawPassword) password.AppendChar(c);
using (var authenticationManager = new AuthenticationManager()) //HELPER CLASS TO OBTAIN ACCESS TOKEN
using (var context = authenticationManager.GetContext(site, user, password))
{
//RETRIVING LIST TITLE - WORKS FINE
/*
Web web = context.Web;
context.Load(web.Lists,
lists => lists.Include(list => list.Title,
list => list.Id));
context.ExecuteQuery();
foreach (SP.List list in web.Lists)
{
Console.WriteLine(list.Title);
}
*/
//RETRIVING LIST ITEM
Web myWeb = context.Web;
SP.List myList = myWeb.Lists.GetByTitle("List_of_Items");
SP.ListItemCollection listItemCollection = myList.GetItems(CamlQuery.CreateAllItemsQuery());
context.Load(listItemCollection,
eachItem => eachItem.Include(
item => item,
item => item["Title"],
item => item["ID"]
)
);
context.ExecuteQuery();
foreach (SP.ListItem listItem in listItemCollection)
{
Console.WriteLine("ID: " + listItem["ID"].ToString() + "Title: " + (string)listItem["Title"].ToString());
}
Console.ReadKey();
}
}
}
}
API permissions
API permissions
It doesn't look like permission issue on checking your app permissions or Code issue.
However, looking at the below line :
SP.ListItemCollection listItemCollection = myList.GetItems(CamlQuery.CreateAllItemsQuery());
You are trying to bring in all the items.
A similar behavior is observed of returning the empty items when the list is a very large list (>5000 or more than 12 lookup columns) or the list hits a list threshold)
If you are falling on the above scenario - you could create a index and filter the items.
You can use CAML query to filter the items instead of trying to fetch all the items in a single go !
Reference for CAML query :
https://techcommunity.microsoft.com/t5/sharepoint/filtering-list-item-using-caml-query-in-sharepoint/m-p/1415904
https://sharepoint.stackexchange.com/questions/94631/filtering-list-using-caml-query-and-binding-it-to-dropdown-in-c
Also, I would check whether the items have a item level permission.
List settings -> Advanced Settings
Ideally, you should not encounter this issue because of the above, however this settings increases number of the scopes and may cause to hit the threshold sooner because.

Adding to Sharepoint List as Anonymous user

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.

How to programmatically retrieve SharePoint My-Sites users' blog posts using C#?

I managed to access user profile content:
using (SPSite ospSite = new SPSite("http://localhost:80/"))
{
ServerContext s = ServerContext.GetContext(ospSite);
UserProfileManager profileManager = new UserProfileManager(s);
UserProfile p = profileManager.GetUserProfile("some_user");
// e.g. responsibility retrieval
var r = p["SPS-Responsibility"];
var responsibilities = r.GetTaxonomyTerms();
}
But I don't know how to access users' blog posts collection.
Any advice?
Use the PersonalSite property of UserProfile object to retrieve the user's My Site.
In the SPSite loop through, child SPWeb objects which are of template "Blog". Check out the templates names here:
http://blogs.msdn.com/b/richin/archive/2011/07/04/sharepoint-2010-site-template-names.aspx
Once you find the blog site, you can simply access the items in "Posts" List of the SPWeb object.

linq to sharepoint datacontext ignore user permission

I'm useing 'Linq to SharePoint' and when I get a SharePoint context the list is empty (user haven't permission to this list).
using (SystemOcenContextDataContext ctx = new SystemOcenContextDataContext("url"))
{
// my code
}
I have tried something like this:
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SystemOcenContextDataContext ctx = new SystemOcenContextDataContext("url"))
{
// my code
}
});
but the context lists are still empty :( Any ideas?
this is another bug :) I find solution:
http://blogs.msdn.com/b/sowmyancs/archive/2010/09/19/linq-to-sharepoint-and-runwithelevatedprivileges.aspx

Categories