Get runtime error with Sharepoint 365 modern experience in C# code - c#

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;
}
}

Related

Sharepoint online CSOM generate list item display url

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

C# Office 365 Sharepoint File Download - ServerObjectNullReferenceException

I'm trying to get a list of file URLs from a SharePoint list but keep running into a ServerObjectNullReferenceException every time I try to access a property from the File.
Can't seem to find a way to load this Server Object from the ClientContext or through the ListItemCollection itself.
What am I missing?
SecureString passWord = new SecureString();
foreach (char c in "password".ToCharArray()) passWord.AppendChar(c);
ClientContext clientContext = new ClientContext("url");
context.Credentials = new SharePointOnlineCredentials("username", passWord);
var list = clientContext.Web.GetList("/Files/Apps/");
var listItems = list.GetItems(new CamlQuery());
clientContext.Load(listItems,
items => items.Include(
item => item.File));
clientContext.ExecuteQuery();
// Any time I access item.File I get the ServerObjectNullReferenceException
foreach (var item in listItems)
{
string test = String.Format("{0}", item.File.ServerRelativeUrl);
}

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.

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.

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);
}
}

Categories