Wednesday, September 9, 2015

Authenticate to Office 365 and SharePoint Online option #1 - CSOM using SharePointOnlineCredentials object from C#


When working on SharePoint Online as a new developer, there is always some confusion how to connect and authenticate to the SharePoint site. I’m summarizing all the different authenticate ways so my developers could choice one appropriate approach for their projects.
 
In this blog, I’ll illustrate the CSOM C# example using SharePointOnlineCredentials object. In this case, you need to pass the user name and password. You need to add Microsoft.SharePoint.Client.dll and Microsoft.SharePoint.Client.Runtime.dll references.

 

using System;
using System.Security;
using Microsoft.SharePoint.Client;
 

namespace CSOM.Example
{
    class Program
    {

        static void Main(string[] args)
        { 

            // Site URL, user name, and password

            string webUrl = "https://mycompany.sharepoint.com/sites/SPDEV";

            string userName = "user@myconpony.com";

            string password = "password";
 

            // Convert the string passowrd to SecureString

            SecureString securePassword = new SecureString();

            foreach (char c in password)

            {

                securePassword.AppendChar(c);

            } 

 

            using (var context = new ClientContext(webUrl))

            {

                context.Credentials = new SharePointOnlineCredentials(userName, securePassword);

                context.Load(context.Web, w => w.Title);

                context.ExecuteQuery();

 

                Console.WriteLine("Your site title is: " + context.Web.Title); 

                var list = context.Web.Lists.GetByTitle("TestList");

                context.Load(list);

                context.ExecuteQuery();

                Console.WriteLine("Your list title is: " + list.Title);

                CamlQuery query = CamlQuery.CreateAllItemsQuery(100);

                ListItemCollection items = list.GetItems(query); 

                context.Load(items);

                context.ExecuteQuery();

                foreach (ListItem listItem in items)

                {

                    // We have all the list item data. For example, Title.

                    Console.WriteLine("Your item title is: " + listItem["Title"]);

                }

            }

        } 

    }

}

No comments:

Post a Comment