CSOM : Exception of type ‘System.OutOfMemoryException’ was thrown

I am trying to get the details of users from User Profiles using CSOM. I have a list of users in Excel file(approx 20000).

I am reading the excel file and storing data in DataTable, i am iterating over the DataTable rows and trying to get details for each of the user using CSOM.

foreach (DataRow row in Inputtbl_ExcelFile.Rows)         {             GroupCollection grps1;             User user;             i++;             string loginName = "";             try             {                 loginName = row["UserID"].ToString();                 //loginName = @"dom434567";                 #region GetUserDetails                      user = clientContext.Web.SiteUsers.GetByLoginName(loginName);                     clientContext.Load(user, user1 => user1.LoginName, user1 => user1.Email, user1 => user1.Groups, user1 => user1.Id);                      grps1 = user.Groups;                     clientContext.Load(grps1, groups => groups.Include(group => group.Title, group => group.Users, group => group.Id));                     clientContext.ExecuteQuery();                  string groupName = string.Empty;                 if (grps1.Count == 0)                     groupName = "NT AUTHORITY\authenticated users";                 foreach (Group gr in grps1)                 {                     groupName = groupName + gr.Title + ";";                 }                 #endregion                  #region UserProf                 //// PeopleManager class provides the methods for operations related to people                 PeopleManager peopleManager = new PeopleManager(clientContext);                  PersonProperties personProperties = peopleManager.GetPropertiesFor(loginName);                  clientContext.Load(personProperties);                 clientContext.ExecuteQuery();                  string Sector = personProperties.UserProfileProperties["Sector"];                 #endregion                   Outputtbl.Rows.Add(i, user.Id, loginName.Replace("i:0#.w|", ""), user.Email, groupName, "Success", Sector);              }             catch (Exception ep)             {                 Outputtbl.Rows.Add(i, "", loginName.Replace("i:0#.w|", ""), "", "", "Failed ," + ep.Message, "");                  Console.WriteLine(ep.Message);             }             clientContext.Dispose();         } 

Now the issue is after some point of time, approx after it has iterated for 2000 items or sometimes 1500 or sometimes even after 3000 items, it throws an error at line :

user = clientContext.Web.SiteUsers.GetByLoginName(loginName); 

Exception of type ‘System.OutOfMemoryException’ was thrown.

I have gone through various article on internet and I understand that this is not related physical memory space but is given slot available at one time.

Can anybody please help me understand if there is any other issue in code or if i can improve code?

How to upload document file and its version file using csom in C#

I have downloaded a document file (current version) and its version history files (old version files) from one of my sharepoint site list. Now, I want to upload that current version file into another site list. After uploading the current version file, I need to upload its version files into _vti_history folder and update version information in current version file.

I can upload the current version file by using below csom code:

using (var clientContext = new ClientContext(url)) {      using (var fs = new FileStream(fileName, FileMode.Open))      {          var fi = new FileInfo(fileName);          var list = clientContext.Web.Lists.GetByTitle(listTitle);          clientContext.Load(list.RootFolder);          clientContext.ExecuteQuery();          var fileUrl = String.Format("{0}/{1}", list.RootFolder.ServerRelativeUrl, fi.Name);      Microsoft.SharePoint.Client.File.SaveBinaryDirect(clientContext, fileUrl, fs, true);  } 

}

But, I don’t know how to upload the version file and update version info in actual file.

Can anyone help me to achieve this in C# using csom?

Returns all values from all columns in a list (CSOM)

I’m stuck to something probably very basics

So the idea is the following: I have a list with 4 columns : Title, CostCenter, City, currency

Via CSOM, I’d like to read this list, so I did something like that:

ClientContext SPcontext = new ClientContext("MySharepointsite");          Web web = SPcontext.Web;           List list = web.Lists.GetByTitle("ListTest");          CamlQuery query = CamlQuery.CreateAllItemsQuery(100);          ListItemCollection items = list.GetItems(query);          SPcontext.Load(list);          SPcontext.Load(items);          SPcontext.ExecuteQuery();           foreach (ListItem listItem in items)          {                Console.Writeline(FieldName = listItem["Title"].ToString());               Console.Writeline(listItem["City"].ToString());           } 

But it returns me the following error message:

Microsoft.SharePoint.Client.PropertyOrFieldNotInitializedException: ‘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.’

I know that it’s comming from my line:

Console.Writeline(listItem["City"].ToString()); 

because I remove it, it works

Any idea of how could I do that?

Thank you for your help 🙂

create list template from list in SharePoint online & download the template using CSOM in Powershell 2013

Trying to create a list template from custom list using Powershell in SharePoint online and trying to download the template on my local machine.

How to create list template achieve above requirement

Updates in question :- How to create list template using client side object model in PowerShell? suggest links..

SharePoint Online: Get Document Library Children Count Using CSOM

My requirement is to get the children item count of Document Library using CSOM. The count should only be the immediate children count, and should not include the sub-children count. I am trying to use below code to achieve this:

var newObjClientContext = this.GetSharePointClientContext(accessToken, fullUri); WebCollection collWeb = newObjClientContext.Web.GetSubwebsForCurrentUser(new SubwebQuery()); var documentLibrary = newObjClientContext.Web.Lists.GetById(docID);  ListItemCollection ltitems = null;  string vquery = @"<View >                 <Query>                     <Where>                          <Or>                              <Eq>                                 <FieldRef Name='FSObjType' />                                  <Value Type='Lookup'>1</Value>                             </Eq>                              <Eq>                                 <FieldRef Name='FSObjType' />                                  <Value Type='Lookup'>0</Value>                             </Eq>                              </Or>                          </Where>                         <OrderBy><FieldRef Name='FileLeafRef' Ascending='TRUE'></FieldRef></OrderBy>                                                             </Query>                     <RowLimit>" + recCount + @"</RowLimit>                     </View>";  CamlQuery camlQuery = new CamlQuery();  camlQuery.ViewXml = vquery; ltitems = documentLibrary.GetItems(camlQuery); newObjClientContext.Load(documentLibrary); newObjClientContext.Load(ltitems, lists => lists.IncludeWithDefaultProperties(l => l.ParentList));  newObjClientContext.ExecuteQuery();  int totalcount = documentLibrary.ItemCount; //It includes count of all the items present at all levels. 

Can anyone suggest how can I get children count in above step?

CSOM Copy List Items

I was create Ribbon Custom Action, and try to copy list items selected to same list, but F12 error? what is the problem?

enter image description here

function runCode() {     var targetListItem;     var values = SP.ListOperation.Selection.getSelectedItems();     var clientContext = new SP.ClientContext.get_current();     var listId = SP.ListOperation.Selection.getSelectedList();     var targetList = clientContext.get_web().get_lists().getById(listId);     targetListItem = targetList.getItemById(values[0].id);     clientContext.load(targetListItem);     clientContext.executeQueryAsync(function () {         var itemCreateInfo = new SP.ListItemCreationInformation();         var oListItem = targetList.addItem(itemCreateInfo);          oListItem.set_item('Title', targetListItem.get_item('Title'));           oListItem.update();         clientContext.load(oListItem);          clientContext.executeQueryAsync(function(){             SP.UI.Notify.addNotification('Item created!', false);             SP.UI.ModalDialog.RefreshPage(SP.UI.DialogResult.OK);        },Function.createDelegate(this, this.onQueryFailed));     },Function.createDelegate(this, this.onQueryFailed));    }     function onQueryFailed(sender, args) {         alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());     } 

Error:

Sys.ArgumentUndefinedException: The value cannot be null. Parameter name: method

SharePoint Online CSOM CAML query problem in view

I have a pages library in sharepoint online with 2 views.

Custom view – (I have added a condition in the view based on a content type) – contains 500 items, It has got 100 items where title starts with “abc”

Default view – It has 4 items and all items have title starting with “abc” (Don’t know why it is showing only 4 items, there is no filter condition and I am expecting all 504 items to appear in the view) – but shows only 4 items

I want to write a CAML query in CSOM on custom view where title begins with “abc”

<View>     <ViewFields>         <FieldRef Name="Title" />     </ViewFields>     <Query>         <Where>             <BeginsWith>                 <FieldRef Name="Title" />                 <Value Type="Text">abc</Value>             </BeginsWith>         </Where>     </Query> </View> 

Query executes fine but shows only 4 items, looks like it is showing items from default view but I want to show items from custom view.

I can load my custom view and use view query

Microsoft.SharePoint.Client.View view = oList.Views.GetByTitle("Custom View");                 rentalSiteClientContext.Load(view);                 rentalSiteClientContext.ExecuteQuery();                 query.ViewXml = view.ViewQuery                 ListItemCollection collListItems = oList.GetItems(query);                 rentalSiteClientContext.Load(collListItems);                 rentalSiteClientContext.ExecuteQuery(); 

this is still returning 4 items.