rs1
rs1

Reputation: 82

Sharepoint collection has not been initialized in asp.net on button click - C# asp.net

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("[email protected]", 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

Upvotes: 0

Views: 5416

Answers (1)

Seiya Su
Seiya Su

Reputation: 1874

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

Upvotes: 1

Related Questions