C# Console Application and Office 365
With some if the things I have been doing recently I needed to create a test console application and connect it to Office 365 for testing API calls and a few other things. As I started out I realized it would be useful to write out the steps I took to get it to work, even if I am only the one that looks at them again.
Firstly, I created a new project in Visual Studio.
Now we have a project, we can install the SharePoint Online NuGet Package to allow us to actually connect with the right references. This is done by launching the “NuGet” windows in Visual Studio and running:
To read more about these components, you can browse to: https://www.nuget.org/packages/Microsoft.SharePointOnline.CSOM. Once it has finished installing your references should now look like this:
Now let’s write some code. Add the following using statements.
Now I added a class for storing the values needed for the site, username and password.
Now we can add some context code that will authenticate us against to Office 365.
Next just some simple code to iterate through the lists in the site.
Finally, modify the “Main” class to call the Lists method.
This code when ran will simply authenticate and then write out the list name in the specified site.
As you can see that was pretty straight forward to connect and retrieve. If we wanted to upload a file to Office 365 then there are various methods of doing this, one of which is based on saving the straight binary file direct to Office 365. I have added the following methods. For more details on the method you can use the following link:
Next I have updated the configuration class to store two new values.
The core method of the console is then updated to call the file upload method.
Once ran the file gets uploaded into the Office 365 SharePoint site.
There are other ways of doing this, by using OAuth tokens instead that utilize the Client ID and Client Secret that we would create. We will look at that approach later on.