0

I am new to Sharepoint and after referring to url - Access SharePoint online using client object model- Forbidden error, I was successfully able to connect to sharepoint and retrieve details in Console application C#. My problem is when I moved the same code to an asp.net website, it gives me Collection has not been initialized error. Here is the code

using (ClientContext clientContext = new ClientContext("https://.../sites/.../"))
        {
            SecureString passWord = new SecureString();

            foreach (char c in "abcdefghijklmnop".ToCharArray()) passWord.AppendChar(c);
            clientContext.Credentials = new SharePointOnlineCredentials("myname@mydomain.com", passWord);
            List list = clientContext.Web.Lists.GetByTitle("ABC DEF");
            CamlQuery camlQuery = new CamlQuery();
            camlQuery.ViewXml = "<View><RowLimit>1200</RowLimit></View>";
            ListItemCollection collListItem = list.GetItems(camlQuery);
            clientContext.Load(collListItem, li => li.Include(
                            pi => pi.Id,
                            pi => pi["Title"],
                            pi => pi["Application"],
                            pi => pi["URL"],
                            pi => pi["AIR_x0020_ID"]

                ));

            clientContext.ExecuteQuery();
            List<string> listofapplications = new List<string>();
            foreach (ListItem oListItem in collListItem)
            {
                { Console.WriteLine(oListItem["Title"] + ", Application " + oListItem["Application"]); }
            }
            Console.ReadLine();
        }

It gives me the error at foreach(Listitem oListItem in collListItem) :

An exception of type 'Microsoft.SharePoint.Client.CollectionNotInitializedException' occurred in Microsoft.SharePoint.Client.Runtime.dll but was not handled in user code

Additional information: The collection has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.

Here is the detailed error:

Microsoft.SharePoint.Client.CollectionNotInitializedException was unhandled by user code HResult=-2146233079 Message=The collection has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.
Source=Microsoft.SharePoint.Client.Runtime StackTrace: at Microsoft.SharePoint.Client.ClientObjectCollection`1.d__0.MoveNext() at Home.btn_Click(Object sender, EventArgs e) in c:\Users\rakesh.a.srivastava\Documents\Visual Studio 2015\WebSites\DNSProvisioningPortal\Home.aspx.cs:line 45 at System.Web.UI.WebControls.Button.OnClick(EventArgs e) at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
InnerException:

please note I am not having any trouble in the console application but asp.net button click operation. I have added the Client and Client.Runtime references as well! I am unable to understand why it works in Console but not in the website. Am I missing any namespace, reference? I have referred these URLs The collection has not been initialized, Sharepoint field has not been initialized in C#, Sharepoint Client Object Model The property or field has not been initialized, but nothing tells me anything about my issue. Please help. Thanks

rs1
  • 82
  • 2
  • 6

1 Answers1

1

Based on my test, some times we can ignore the exception in the aspnet project. (For your code, you need to replace the ["XXX"] with Client_XXX)

Preparation

Install Microsoft.SharePointOnline.CSOM by NuGet package manager to project.

My Test code: A Extensions method first(optional for you)

public static class CSOMExtensions
    {
        public static Task ExecuteQueryAsync(this ClientContext clientContext)
        {
            return Task.Factory.StartNew(() =>
            {
                clientContext.ExecuteQuery();
            });
        }
    }

Replace some code from your post with mine:

 List list = clientContext.Web.Lists.GetByTitle("CustomList1");
 CamlQuery camlQuery = new CamlQuery();
 camlQuery.ViewXml = "<View><RowLimit>1200</RowLimit></View>";
 ListItemCollection collListItem = list.GetItems(camlQuery);

 clientContext.Load(collListItem, li => li.Include( 
                        pi => pi.Client_Title
                      //pi => pi["Application"],
                      // pi => pi["AIR_x0020_ID"]
            ));

//clientContext.ExecuteQueryAsync();

Task t2 = clientContext.ExecuteQueryAsync();

await t2.ContinueWith((t) =>
{
   foreach (ListItem oListItem in collListItem)
   {
     System.Diagnostics.Debug.WriteLine(oListItem.Client_Title); 
   }
});

If we use the ["Title"] directly, it will crash in the aspnet but the Client_XXX won't on my side.

I have not deeper research why and have not try the custom fields. I will research more while i have time

Seiya Su
  • 1,836
  • 1
  • 7
  • 10
  • Hello Seiya, I do not see Client_Title, Am i missing some reference? `using System; using Microsoft.SharePoint.Client; using System.Security; using System.Threading.Tasks;` **Error:** _ListItem does not contain a defintion for Client_Title, are you missing any reference_ – rs1 Aug 13 '18 at 08:59
  • I add the CSOM dlls by Nuget, you can try it. I guess the local dlls from the VS SharePoint template maybe not latest, I am not sure this. – Seiya Su Aug 13 '18 at 09:16
  • Great, It worked!!! Kept your code and updated my dlls and now everything works smoothly :) Thank you so much :) I have marked it as answer unfortunately it does not register my vote. For all who are facing this issue, use the above code and remove all sharepoint references! from NuGet package manager, search for Microsoft.SharePointOnline.CSOM and Install! That should solve the issue. _Thanks Seiya! :)_ – rs1 Aug 13 '18 at 10:13