Skip to main content

CSOM Example



Once I was asked to develop a solution that was not to be installed on the SharePoint server neither I was allowed to create a webpart solution that could be deployed on SharePoint server. The best solution that I found was to create Desktop Application, and delivering it executable file.
As it was a desktop application we need to use CSOM. In this blog I will show you a basic code demo to interact with SharePoint server.
Validate User
1.       When you are on same domain as SharePoint server and use windows credentials to login.
using (ClientContext ctx = new ClientContext(URL))
{
}
2.       When you are in different domain or want to login as different user.
using (ClientContext ctx = new ClientContext(URL))
{
  ctx.Credentials = new NetworkCredential(UserName,Password,Domain);
}
3.  When you want to login as FBA User
using (ClientContext ctx = new ClientContext(URL))
{
  ctx.AuthenticationMode = ClientAuthenticationMode.FormsAuthentication;
                            ctx.FormsAuthenticationLoginInfo = new FormsAuthenticationLoginInfo(UserName, Password);
}

Query for Sites
 Add below code on authentication success.
     ctx.Load(ctx.Site); // Query for Web
     ctx.ExecuteQuery(); // Execute
     Site oSite = ctx.Site;
     Web rootWeb = ctx.Site.RootWeb;

Query for Lists/Libraries
                 ctx.Load(rootWeb);
      ctx.ExecuteQuery();
      List list = null;
      try
      {
        list = rootWeb.Lists.GetByTitle(ListName);
        ctx.Load(list, tList => tList.Title);
        ctx.ExecuteQuery();
      }
      catch (Exception e)
      {

      }
Thanks & Regards,
Keyur Pandya
     

Comments