0
votes

I am new to Sharepoint and currently I want to write a function where I can read and write data to Sharepoint pages. This is the structure of the URL I want to connect to read and write data: https://mycompany.sharepoint.com/sites/SubSite/SubSite1/SitePages/Home.aspx
Then, I open the connection to it by using:

ClientContext clientContext = new ClientContext("https://mycompany.sharepoint.com/sites/SubSite/SubSite1/");
clientContext.Credentials = new SharePointOnlineCredentials("[email protected]", password);

I use SecureString for the password
Then, I load site pages in to a list and read each field to examine:

List colList = clientContext.Web.Lists.GetByTitle("Site Pages");
FieldCollection colfield = colList.Fields;
IEnumerable<Microsoft.SharePoint.Client.List> resultCollection = clientContext.LoadQuery(
        clientContext.Web.Lists.Include(
        list => list.Title,
        list => list.Id));
clientContext.Load(colList);
clientContext.Load(colfield);
clientContext.ExecuteQuery();

Then I loop through every field to examine

for(int i = 1; i <= 4; i++){  
    ListItem lst = colList.GetItemById(i);
    foreach (Field field in colfield){
        clientContext.Load(field);
        clientContext.ExecuteQuery();
        var val = lst[field.Title];
    }
}

I figured out that there are some fields in colList, such as: DataSource, etc. containing this exception:

The property or field has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested

My question is how can I properly connect to Sharepoint site pages to read and write data in them?

1

1 Answers

0
votes

You are iterating through all the fields of colList but including only Id & Title fields in

 clientContext.Web.Lists.Include(
        list => list.Title,
        list => list.Id));

That's why you are getting above exception.

You have to Include all the fields you want to retrieve OR just load the list clientContext.Load(colList); and don't Include anything if you want to retrieve all the fields.