Windows Form Application reading data from SharePoint Online
site.

A lot has already been written for reading data from a SP on-premises
site collections. But it took me some time to actually understand how to read
data from a SharePoint Online site.

First I would like to list down the errors which you may
face if the same code written for the site using Windows authentication is used
for reading data from #SPO Site.

1. Invalid username and password.

2. User not authorized.

3. Remote server access forbidden.

The following code lines(for loading site context) works
fine in case we have Windows authentication for the site:

ClientContext context =new ClientContext("SiteCollectionUrl");

Web web = context.Web;

context.Load(context.Web);

context.ExecuteQuery();

 

 

In case of Claims based authentication (e.g. in SPO sites):

The user must be able to sign into the remote system interactively. First, the user signs into
SharePoint through the federated authentication provider, and SharePoint must
issue its authentication cookies. Second, the code must retrieve the
authentication cookies. Third, those cookies must be added to the ClientContext object.

The article on msdn talks about how the forms application interacts with SPO using claims.

http://msdn.microsoft.com/en-us/library/hh147177%28v=office.14%29.aspx

Below are the steps which can be followed for reading data from SPO site:


  1. Download sample project from the msdn link.

  2. Right click on your solution and add a new
    project.

  3. Right click on this new project and add
    existing item to the project.

  4. Browse to the downloaded project folder and add
    ClaimClientContext.cs, ClaimsWebAuth.cs, Constants.cs,
    CookieReader.cs
    to your new project.

  5. Add reference of this project to your main
    project.

After these steps you can use the following code to load
context of the SPO Site:

string targetSite ="SPO
Site Url";

using (ClientContext ctx = ClaimClientContext.GetAuthenticatedContext(targetSite))

            {

                if (ctx != null)

                {

                    ctx.Load(ctx.Web); // Query for Web

                    ctx.ExecuteQuery(); // Execute

                    Console.WriteLine(ctx.Web.Title);

                }

            }

 

Thanks !!

Swati