Read SharePoint List with CSOM

        public static List<WorkLocation> GetListItemsWorkLocation(string url, string listName)
        {
            Log.Information("Method Start - GetListItemsWorkLocation(SP Url, ListName, ColumnName)\n\tSP Url: {url}\n\tListName: {listName}\n\tColumnName: {columnName}\n", url, listName);

            // columnName = the underlying field name NOT the display name!
            // listName = the display list name NOT the url list name!
            List<WorkLocation> list = new List<WorkLocation>();

            try
            {
                using (var context = new SP.ClientContext(url))
                {
                    context.Credentials = JP_Utility.GetSharePointCredentials();

                    SP.List oList = context.Web.Lists.GetByTitle(listName);

                    // an empty/blank CAML query string will return all list items!
                    SP.CamlQuery camlQuery = new SP.CamlQuery();
                    SP.ListItemCollection collListItem = oList.GetItems(camlQuery);

                    context.Load(collListItem);

                    context.ExecuteQuery();

                    foreach (SP.ListItem oListItem in collListItem)
                    {
                        WorkLocation myObject = new WorkLocation()
                        {
                            Location = oListItem["Title"].ToString(),
                            Hub = oListItem["Hub"].ToString(),
                        };
                        list.Add(myObject);
                    }

                    // list.Sort();
                }
            }
            catch (SP.PropertyOrFieldNotInitializedException ex)
            {
                Log.Error("Property not initialized: {msg}", ex.Message);
                Log.Error("Property not initialized: {msg}", ex.StackTrace);
            }
            catch (SP.InvalidQueryExpressionException ex)
            {
                Log.Error("Invalid LINQ query: {msg}", ex.Message);
                Log.Error("Invalid LINQ query: {msg}", ex.StackTrace);
            }
            catch (SP.ClientRequestException ex)
            {
                Log.Error("Bad request: {msg}", ex.Message);
                Log.Error("Bad request: {msg}", ex.StackTrace);
            }
            catch (SP.ServerException ex)
            {
                Log.Error("Exception on server: {msg}", ex.Message);
                Log.Error("Exception on server: {msg}", ex.StackTrace);
            }
            catch (Exception ex)
            {
                Log.Error("Error Message is: {msg}", ex.Message);
                Log.Error("Error Message is: {msg}", ex.StackTrace);
            }
            finally
            {
                Log.Information("Method End - GetListItemsWorkLocation(SP Url, ListName)\n");
            }

            return list;
        }

Leave a comment

Your email address will not be published. Required fields are marked *