Skip to content

Instantly share code, notes, and snippets.

@jaycdave88
Last active February 8, 2017 19:57
Show Gist options
  • Save jaycdave88/dc8ec99467e43ea8ee54d4ba5252d210 to your computer and use it in GitHub Desktop.
Save jaycdave88/dc8ec99467e43ea8ee54d4ba5252d210 to your computer and use it in GitHub Desktop.
Microsoft Graph Service attempt to use Microsoft Graph CSharp SDK
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Http.Headers;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Threading.Tasks;
using System.Web;
using Microsoft.Graph;
namespace OneDrive_SDK_Daemon
{
[DataContract]
internal class AzureActiveDirectoryTokenFormat
{
[DataMember]
internal string token_type { get; set; }
[DataMember]
internal string access_token { get; set; }
public IGraphServiceClient graphServiceClient { get; set; }
public DriveItem folder = new DriveItem();
public List<string> userEmails = new List<string>();
private static readonly AzureActiveDirectoryTokenFormat instance = new AzureActiveDirectoryTokenFormat();
public static AzureActiveDirectoryTokenFormat Instance
{
get { return instance; }
}
public async Task<string> CreateToken()
{
return AzureActiveDirectoryTokenFormat.Instance.access_token;
}
}
public class Program
{
private const string ServiceClientId = "";
private const string ServiceClientSecret = "";
private const string ServiceTenantName = "";
static void Main()
{
//Will create a POST, Service/Daemon flow to return a access_token to be used with the
//Microsoft Graph API Service to return OneDrive for business custodian data.
//CreateToken();
Task.Run(async () =>
{
await GetOneDriveData();
}).GetAwaiter().GetResult();
}
public static async Task<string> CreateToken()
{
string accessToken;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(string.Format(
"https://login.microsoftonline.com/{0}/oauth2/token",
ServiceTenantName));
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
string postData = @"grant_type=client_credentials";
postData += "&resource=" + HttpUtility.UrlEncode("https://graph.microsoft.com");
postData += "&client_id=" + HttpUtility.UrlEncode(ServiceClientId);
postData += "&client_secret=" + HttpUtility.UrlEncode(ServiceClientSecret);
byte[] data = encoding.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
using (var response = request.GetResponse())
{
using (var stream = response.GetResponseStream())
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(AzureActiveDirectoryTokenFormat));
AzureActiveDirectoryTokenFormat token =
(AzureActiveDirectoryTokenFormat)(serializer.ReadObject(stream));
string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", token.token_type, " ",
token.access_token);
accessToken = token.access_token;
AzureActiveDirectoryTokenFormat.Instance.access_token = token.access_token;
Console.WriteLine("Access Token: \n {0}", token.access_token);
}
}
return accessToken;
}
public static GraphServiceClient GetAuthenticatedClient(string accessToken = null)
{
try
{
GraphServiceClient graphClient = new GraphServiceClient(
new DelegateAuthenticationProvider(
#pragma warning disable 1998
async (requestMessage) =>
#pragma warning restore 1998
{
accessToken = await AzureActiveDirectoryTokenFormat.Instance.CreateToken();
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
}));
AzureActiveDirectoryTokenFormat.Instance.graphServiceClient = graphClient;
return graphClient;
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
public static async Task GetOneDriveData(bool firstRun = true, bool showUserSpecific = false)
{
var expandValue = "thumbnails,children";
try
{
if (firstRun)
{
//helper method to access the auth_token
GetAuthenticatedClient(await CreateToken());
//Returns a collection of all users
var allUsers = (GraphServiceUsersCollectionPage)await AzureActiveDirectoryTokenFormat.Instance.graphServiceClient.Users.Request().GetAsync();
//Adds all the User.emails to the collection
foreach (var user in allUsers)
{
AzureActiveDirectoryTokenFormat.Instance.userEmails.Add(user.Mail);
}
}
else
{
// fetch all users users's root
foreach (var userEmail in AzureActiveDirectoryTokenFormat.Instance.userEmails)
{
var root = AzureActiveDirectoryTokenFormat.Instance.folder =
await AzureActiveDirectoryTokenFormat.Instance.graphServiceClient.Drives[userEmail].Root
.Request().Expand(expandValue).GetAsync();
Console.Write("Folder Name: {0}", root.Name);
foreach (var item in AzureActiveDirectoryTokenFormat.Instance.folder.Children)
{
var children = await AzureActiveDirectoryTokenFormat.Instance.graphServiceClient.Drives[userEmail].Items[item.Id]
.Request().Expand(expandValue).GetAsync();
Console.WriteLine(children.Name);
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
await GetOneDriveData(false);
Console.ReadLine();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment