Tuesday, January 20, 2015

Connecting SharePoint 2013 Office 365 through CSOM

In order to connect to SharePoint Office 365 through CSOM you need to have following Dlls that need to be added to visual studio project. These dlls are:

Microsoft.SharePoint.Client
Microsoft.SharePoint.Client.Runtime.dll
Microsoft.SharePoint.Client. Taxonomy.dll
Microsoft.SharePoint.Client.UserProfiles.dll

Below code can be used to create a connection to SharePoint 2013 Office 365

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)
        {           
                string webUrl = "https://abc.sharepoint.com";
                Console.WriteLine("Enter your user name (ex: john@mytenant.microsoftonline.com):");
                string userName = Console.ReadLine();
                Console.WriteLine("Enter your password.");               
                SecureString password = GetPasswordFromConsoleInput();
                using (var context = new ClientContext(webUrl))
                {
                    context.Credentials = new SharePointOnlineCredentials(userName, password);
                    context.Load(context.Web, w => w.Title);
                    context.ExecuteQuery();
                    Console.ForegroundColor = ConsoleColor.White;
                    Console.WriteLine("Your site title is: " + context.Web.Title);
                    Console.ForegroundColor = defaultForeground;
                  
                }
           
        }
        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