Monday, 6 May 2013

Using the C# CSOM to interact with SharePoint Online

So, I had a requirement recently to allow a client to interact with their SPOnline site from their on-prem network, essentially being able to sync data from their on-prem LoB apps to their SPOnline site.

As any sp dev knows there is one main way of interacting with SharePoint remotely, that is through the supplied web services, this can be done either through interacting directly with the web services or by using the SharePoint client site object model which essentially just wraps a basic API around the web services, so its your preference on what you want to use.

Now with the CSOM any interactions with SharePoint are based around the context, to set up the context you need to pass in the credentials and authenticate the accessing user, in SP 2010 this was a feat to accomplish as there was no real way to pass in an authentication token to the context, with the release of SP2013 MS have made this significantly simpler, you can call in a class called "SharePointOnlineCredentials" this will handle any authentication you should need to do. this class is included in version 15 of the Microsoft.SharePoint.Client dll

Depending on how you have your dev environment set up you may encounter a "FileNotFoundException" pointing to "MSOIDCLIL.dll" this usually occurs if you have VS installed locally and have installed the dev tools but you haven't installed the client sdk, you can check this by navigating to this directory "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\Client", if that dir exists and has the dll then there is a broken link somewhere and you will need to reinstall the sdk, if it doesn't exist then a fresh install of the SharePoint Client SDK here.

By using this you now have open to you the full array of functions you can call with the CSOM that you can now call from your on prem network

Here is the code I have used to PoC the process, please use it as you see fit:


    class Program
    {
        static void Main(string[] args)
        {
            args = new string[] { "CreateProjectList" };
            if (args.Length != 1)
            {
                Console.WriteLine("Instanciate the program with a method parameter:");
                Console.WriteLine(" - GetLists");
                Console.WriteLine(" - CreateProjectList");
            }
            else
            {
                switch (args[0])
                {
                    case "GetLists":
                        Console.WriteLine("Getting lists from Online Site");
                        GetLists();
                        Console.WriteLine("List retrieval complete");
                        break;
                    case "CreateProjectList":
                        Console.WriteLine("Creating projects list in Online Site");
                        CreateProjectList();
                        Console.WriteLine("List creation complete");
                        break;
                }

                Console.ReadKey();
            }
        }

        private class Configuration
        {
            public static string ServiceSiteUrl = "https://{mysite}.sharepoint.com";
            public static string ServiceUserName = "{user}@{365-org}.onmicrosoft.com";
            public static string ServicePassword = "{password}";
        }

        static ClientContext GetContext()
        {
            var securePassword = new SecureString();
            foreach (char c in Configuration.ServicePassword)
            {
                securePassword.AppendChar(c);
            }

            var onlineCredentials = new SharePointOnlineCredentials(Configuration.ServiceUserName, securePassword);

            var context = new ClientContext(Configuration.ServiceSiteUrl);
            context.Credentials = onlineCredentials;

            return context;
        }

        static void GetLists()
        {
            var context = GetContext();
            var results = context.LoadQuery(context.Web.Lists.Include(list => list.Title, list => list.Id));
            context.ExecuteQuery();
            results.ToList().ForEach(x =>
            {
                Console.WriteLine("List: " + x.Title);
            });

            context.Dispose();
        }

        static void CreateProjectList()
        {
            ClientContext clientContext = GetContext();
            Web site = clientContext.Web;

            // Create the project list.
            ListCreationInformation listCreationInfo = new ListCreationInformation();
            listCreationInfo.Title = "Projects";
            listCreationInfo.TemplateType = (int)ListTemplateType.GenericList;
            List list = site.Lists.Add(listCreationInfo);

            // Add the category field to the list.
            Field catField = list.Fields.AddFieldAsXml(@"
                <Field Type='Choice' DisplayName='Category' Format='Dropdown'>
                    <Default>IT</Default>
                    <CHOICES>
                      <CHOICE>IT</CHOICE>
                      <CHOICE>Sales</CHOICE>
                      <CHOICE>Research and Development</CHOICE>
                      <CHOICE>CSR</CHOICE>
                    </CHOICES>
                </Field>
                ", true, AddFieldOptions.DefaultValue);

            // Add list data.
            ListItemCreationInformation itemCreationInfo = new ListItemCreationInformation();
            ListItem listItem = list.AddItem(itemCreationInfo);
            listItem["Title"] = "New public facing website";
            listItem["Category"] = "IT";
            listItem.Update();

            listItem = list.AddItem(itemCreationInfo);
            listItem["Title"] = "New Incident Management System";
            listItem["Category"] = "IT";
            listItem.Update();

            listItem = list.AddItem(itemCreationInfo);
            listItem["Title"] = "New internal sales strategy";
            listItem["Category"] = "Sales";
            listItem.Update();

            listItem = list.AddItem(itemCreationInfo);
            listItem["Title"] = "Youtube product visibility";
            listItem["Category"] = "CSR";
            listItem.Update();

            clientContext.ExecuteQuery();
        }

1 comment: