Tuesday, January 12, 2016

Creating Console Application using Client Side Object Model (CSOM)

1)    Open Visual Studio and create a Console Application.



2)    
Browse Microsoft.SharePoint.Client.dll and  Microsoft.SharePoint.Client.Runtime.dll it to the References.
 

3)    In the next step you have to change the properties of an application.In the build option change the platform target into 64 bit (x64).


4) Create
SPRepositoryBase.cs class and write below code in it for accessing SharePoint site with giving correct credentials of your sharepoint site
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Microsoft.SharePoint.Client;

namespace SampleConsoleApplication
{
    public class ContextDetails
    {
        public string SPUserName
        {
            get
            {
                return "sharepoint";
            }
        }

        public string SPPassword
        {
            get
            {
                return "*****";
            }
        }

        public string Domain
        {
            get
            {
                return "SPDEV.LOCAL";
            }
        }

        public string SPSiteUrl
        {
            get
            {
                return "http://spdev-3:1001";
            }
        }
    }
    public class SPRepositoryBase
    {
        protected ContextDetails _ContextCredentialDetails;
        public SPRepositoryBase()
        {
            _ContextCredentialDetails = new ContextDetails();
        }
        protected ClientContext SPClientContext
        {
            get
            {
                ClientContext clientContext = new ClientContext(_ContextCredentialDetails.SPSiteUrl);
                clientContext.ExecutingWebRequest += new EventHandler<WebRequestEventArgs>(clientContext_ExecutingWebRequest);
                if (!string.IsNullOrEmpty(_ContextCredentialDetails.Domain))
                {
                    clientContext.Credentials = new NetworkCredential(_ContextCredentialDetails.SPUserName, _ContextCredentialDetails.SPPassword, _ContextCredentialDetails.Domain);
                }
                else
                {
                    clientContext.AuthenticationMode = ClientAuthenticationMode.FormsAuthentication;
                    FormsAuthenticationLoginInfo formsAuthInfo = new FormsAuthenticationLoginInfo(_ContextCredentialDetails.SPUserName, _ContextCredentialDetails.SPPassword);
                    clientContext.ValidateOnClient = true;
                    clientContext.FormsAuthenticationLoginInfo = formsAuthInfo;
                }
                return clientContext;
            }
        }
        protected void clientContext_ExecutingWebRequest(object sender, WebRequestEventArgs e)
        {
            e.WebRequestExecutor.WebRequest.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
        }
    }
}


5)
Then write the below code in the Program.cs file and inherit class with SPRepositoryBase
using Microsoft.SharePoint;
using Microsoft.SharePoint.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SampleConsoleApplication
{
    class Program : SPRepositoryBase
    {
        static void Main(string[] args)
        {
            try
            {
                Program p = new Program();
                p.RetrieveRecord();
            }
            catch (Exception ex)
            {

            }
        }

        public void AddRecord()
        {
      
            using (ClientContext context = SPClientContext)
            {
                List spList = context.Web.Lists.GetByTitle("TestList");
                ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
                ListItem spItem = spList.AddItem(itemCreateInfo);
                spItem["Title"] = DateTime.Now.ToString();
                spItem["FirstName"] = "Ahsen";
                spItem["LastName"] = "Khan";

                spItem.Update();
                context.ExecuteQuery();

            }
        }


        public void DeleteRecord()
        {

            using (ClientContext context = SPClientContext)
            {
                List spList = context.Web.Lists.GetByTitle("TestList");
                CamlQuery query = new CamlQuery();
                query.ViewXml = string.Format("<View><Query><Where><Eq><FieldRef Name='FirstName'  /><Value Type='Text'>{0}</Value></Eq></Where></Query></View>", "khan");
                ListItemCollection items = spList.GetItems(query);
                context.Load(spList);
                context.Load(items);
                context.ExecuteQuery();
                if (items != null && items.Count > 0)
                {
                    foreach (ListItem item in items.ToList())
                    {
                        item.Recycle();
                    }
                }
                spList.Update();
                context.ExecuteQuery();
            
            }
        }
        public void RetrieveRecord()
        {

            using (ClientContext context = SPClientContext)
            {
                List spList = context.Web.Lists.GetByTitle("TestList");
                CamlQuery query = new CamlQuery();
                query.ViewXml = string.Format("<View><Query><Where><Eq><FieldRef Name='FirstName'  /><Value Type='Text'>{0}</Value></Eq></Where></Query></View>", "Ahsen");
                ListItemCollection items = spList.GetItems(query);
                context.Load(spList);
                context.Load(items);
                context.ExecuteQuery();
                if (items != null && items.Count > 0)
                {
                    foreach (ListItem item in items.ToList())
                    {
                        Console.WriteLine(item["Title"].ToString());
                    }
                }

                Console.ReadKey();

            }
        }

        public void UpdateRecord()
        {
            using (ClientContext context = SPClientContext)
            {
                List spList = context.Web.Lists.GetByTitle("TestList");
                ListItem oListItem = spList.GetItemById(8);
                if (oListItem != null)
                {
                    oListItem["Title"] = "Updated Title";
                    oListItem.Update();
                    context.ExecuteQuery();
                }
            }

        }
    }
}
6) Now run the console application it will add new record in your SharePoint list


0 comments:

Post a Comment