Tuesday, January 20, 2015


Creating new item in the list using CSOM for SharePoint 2013 Online and retrieving the list items

If incase we happend to create a list item using CSOM for Sharepoint 2013 Online below code can be used.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint;
using System.Security;
namespace GetListCollection
{
    class Program
    {
        static void Main(string[] args)
        {
            ClientContext clientContext = new ClientContext("https://abc.sharepoint.com/");
            Web webUrl=clientContext.Web;
            Console.WriteLine("Enter your user name (ex: abc@microsoft.microsoftonline.com):");
            string userName = Console.ReadLine();
            Console.WriteLine("Enter your password.");
            SecureString password = GetPasswordFromConsoleInput();
            clientContext.Credentials = new SharePointOnlineCredentials(userName, password);

            //Get the list by Title
            List list = webUrl.Lists.GetByTitle("doctest");

            //create a new item
            ListItemCreationInformation creationinfo = new ListItemCreationInformation();
            ListItem item = list.AddItem(creationinfo);

            //Set the title value for the new item
            item["Title"] = "New Item";

            //Update the item
            item.Update();
            clientContext.Load(item);

            //Execute the query to the server
            clientContext.ExecuteQuery();

            //Camlquery to retrieve the item from the custom list
            CamlQuery query = CamlQuery.CreateAllItemsQuery();

            //Get all the items from the list
            ListItemCollection itemcoll = list.GetItems(query);
            clientContext.Load(itemcoll);

            clientContext.ExecuteQuery();

            //Loop through all the items
            foreach (ListItem items in itemcoll)
            {
                //Display the item title field value
                Console.Write(items["Title"].ToString() + " \n ");

            }
            Console.ReadLine();

        }
        private static SecureString GetPasswordFromConsoleInput()
        {
            ConsoleKeyInfo info;

            //Get the user's password as a SecureString
            SecureString securePassword = new SecureString();
            do
            {
                info = Console.ReadKey(true);
                if (info.Key != ConsoleKey.Enter)
                {
                    securePassword.AppendChar(info.KeyChar);
                }
            }
            while (info.Key != ConsoleKey.Enter);
            return securePassword;
        }
    }
}

No comments:

Post a Comment