public static string CreateMsTeamsChannelFolder(string aadAccessToken, string teamId, string channelName) { Tuple <string, string> fileExists = Utils.FileAttachments.CheckIfFileExistsOnTeamsChannel(aadAccessToken, teamId, "/" + channelName); if (fileExists.Item1 != "") { Console.WriteLine("Channel folder exists " + fileExists); return(fileExists.Item1); } var authHelper = new O365.AuthenticationHelper() { AccessToken = aadAccessToken }; Microsoft.Graph.GraphServiceClient gcs = new Microsoft.Graph.GraphServiceClient(authHelper); Microsoft.Graph.DriveItem driveItem = new Microsoft.Graph.DriveItem(); driveItem.Name = channelName; var folder = new Microsoft.Graph.Folder(); driveItem.Folder = folder; try { var result = gcs.Groups[teamId].Drive.Root.Children.Request().AddAsync(driveItem).Result; Console.WriteLine("Folder ID is " + result.Id + " with path " + result.WebUrl); return(result.Id); } catch (Exception ex) { Console.WriteLine("Folder creation failure: " + ex.InnerException); return(""); } }
public DriveAccountService(SiteContext siteContext, TokenService tokenService) { this.SiteContext = siteContext; this.tokenService = tokenService; this.app = tokenService.app; this.Graph = tokenService.Graph; }
public static Tuple <string, string> CheckIfFileExistsOnTeamsChannel(string aadAccessToken, string selectedTeamId, string pathToItem) { var authHelper = new Utils.O365.AuthenticationHelper() { AccessToken = aadAccessToken }; Microsoft.Graph.GraphServiceClient gcs = new Microsoft.Graph.GraphServiceClient(authHelper); Microsoft.Graph.DriveItem fileExistsResult = null; try { fileExistsResult = gcs.Groups[selectedTeamId].Drive.Root.ItemWithPath(pathToItem). Request().GetAsync().Result; } catch { fileExistsResult = null; } if (fileExistsResult == null) { return(new Tuple <string, string>("", "")); } Console.WriteLine("Attachment already exists. We won't replace it. " + pathToItem); return(new Tuple <string, string>(fileExistsResult.Id, fileExistsResult.WebUrl)); }
private async void EventsButton_Click(object sender, RoutedEventArgs e) { graphClient = AuthenticationHelper.GetAuthenticatedClient(); if (graphClient != null) { try { DateTime startDate = DateTime.Now; DateTime endDate = DateTime.Now.AddDays(1).AddTicks(-1); string startDateTime = startDate.ToString("s"); string endDateTime = endDate.ToString("s"); ImgList.Clear(); InfoText.Text = "Connected "; ImgList = await GetEventsAsync(startDateTime, endDateTime); ListEvent.ItemsSource = ImgList; InfoText.Text = "Connected, " + ImgList.Count.ToString() + " Images found"; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("Exception while getting events: " + ex.Message); } } UpdateControls(); }
public DriveAccountService(SiteContext siteContext) { if (Configuration.Type == Configuration.OfficeType.China) { app = ConfidentialClientApplicationBuilder .Create(Configuration.ClientId) .WithClientSecret(Configuration.ClientSecret) .WithRedirectUri(Configuration.BaseUri + "/api/admin/bind/new") .WithAuthority(AzureCloudInstance.AzureChina, "common") .Build(); } else { app = ConfidentialClientApplicationBuilder .Create(Configuration.ClientId) .WithClientSecret(Configuration.ClientSecret) .WithRedirectUri(Configuration.BaseUri + "/api/admin/bind/new") .WithAuthority(AzureCloudInstance.AzurePublic, "common") .Build(); } //缓存Token TokenCacheHelper.EnableSerialization(app.UserTokenCache); //这里要传入一个 Scope 否则默认使用 https://graph.microsoft.com/.default //而导致无法使用世纪互联版本 authProvider = new AuthorizationCodeProvider(app, Configuration.Scopes); //获取Token if (File.Exists(TokenCacheHelper.CacheFilePath)) { authorizeResult = authProvider.ClientApplication.AcquireTokenSilent(Configuration.Scopes, Configuration.AccountName).ExecuteAsync().Result; //Debug.WriteLine(authorizeResult.AccessToken); } //启用代理 if (!string.IsNullOrEmpty(Configuration.Proxy)) { // Configure your proxy var httpClientHandler = new HttpClientHandler { Proxy = new WebProxy(Configuration.Proxy), UseDefaultCredentials = true }; var httpProvider = new Microsoft.Graph.HttpProvider(httpClientHandler, false) { OverallTimeout = TimeSpan.FromSeconds(10) }; Graph = new Microsoft.Graph.GraphServiceClient($"{Configuration.GraphApi}/v1.0", authProvider, httpProvider); } else { Graph = new Microsoft.Graph.GraphServiceClient($"{Configuration.GraphApi}/v1.0", authProvider); } this.SiteContext = siteContext; //定时更新Token Timer timer = new Timer(o => { if (File.Exists(TokenCacheHelper.CacheFilePath)) { authorizeResult = authProvider.ClientApplication.AcquireTokenSilent(Configuration.Scopes, Configuration.AccountName).ExecuteAsync().Result; } }, null, TimeSpan.FromSeconds(0), TimeSpan.FromHours(1)); }
public async Task <Microsoft.Graph.User> Me() { Microsoft.Graph.GraphServiceClient client = await graphTokenService.GetClientForUser(new string[] { "profile" }); Microsoft.Graph.User me = await client.Me.Request().GetAsync(); return(me); }
public DriveAccountService(SiteContext siteContext, TokenService tokenService) { this.SiteContext = siteContext; this.tokenService = tokenService; this.app = tokenService.app; this.authorizeResult = tokenService.authorizeResult; this.authProvider = tokenService.authProvider; this.Graph = tokenService.Graph; }
private void DisconnectButton_Click(object sender, RoutedEventArgs e) { ImgList.Clear(); ListEvent.ItemsSource = ImgList; AuthenticationHelper.SignOut(); graphClient = null; UserInfo.Text = ""; InfoText.Text = "Click on connect button to launch the authentication"; UpdateControls(); }
/// <summary> /// Signs in the current user. /// </summary> /// <returns></returns> public async Task <bool> SignInCurrentUserAsync() { graphClient = AuthenticationHelper.GetAuthenticatedClient(); if (graphClient != null) { Microsoft.Graph.User user = await graphClient.Me.Request().GetAsync(); if (user != null) { string userId = user.Id; UserInfo.Text = "Name:" + user.DisplayName + " and address: " + user.UserPrincipalName; return(true); } } return(false); }
private async void button1_Click(object sender, EventArgs e) { if (!await graphLoginComponent1.LoginAsync()) { return; } //update the user's display fields label1.Text = graphLoginComponent1.DisplayName; label2.Text = graphLoginComponent1.JobTitle; pictureBox1.Image = graphLoginComponent1.Photo; // Do more things with the graph graphClient = graphLoginComponent1.GraphServiceClient; var rootItems = await graphClient.Me.Drive.Root.Children.Request().GetAsync(); BindingSource bindingSource1 = new BindingSource(); dataGridView1.DataSource = bindingSource1; bindingSource1.DataSource = rootItems; dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader); }
public static async Task <Microsoft.Graph.GraphServiceClient> GetGraphServiceClientAsUser() { string accessToken = await GetTocken(); Microsoft.Graph.GraphServiceClient GraphServiceClient = new Microsoft.Graph.GraphServiceClient(Constants.ResourceUrl + "/" + Constants.TenantId, new Microsoft.Graph.DelegateAuthenticationProvider( (requestMessage) => { requestMessage.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", accessToken); UriBuilder ub = new UriBuilder(requestMessage.RequestUri); System.Collections.Specialized.NameValueCollection query = System.Web.HttpUtility.ParseQueryString(ub.Query); query["api-version"] = "1.5"; ub.Query = query.ToString(); requestMessage.RequestUri = ub.Uri; return(Task.FromResult(0)); })); return(GraphServiceClient); }
private async void UploadFile(object sender, RoutedEventArgs e) { var accounts = (await _app.GetAccountsAsync()).ToList(); if (!accounts.Any()) { MessageBox.Show("Please sign in first"); return; } System.Windows.Forms.OpenFileDialog fileDialog = new System.Windows.Forms.OpenFileDialog(); if (fileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { using (var fileStream = File.OpenRead(fileDialog.FileName)) { AuthenticationResult result = null; try { result = await _app.AcquireTokenSilent(BasePermissionScopes, accounts.FirstOrDefault()) .ExecuteAsync() .ConfigureAwait(false); await Dispatcher.Invoke(async() => { Microsoft.Graph.GraphServiceClient graphClient = new Microsoft.Graph.GraphServiceClient(MSGraphURL, new Microsoft.Graph.DelegateAuthenticationProvider(async(requestMessage) => { requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", result.AccessToken); })); // Use properties to specify the conflict behavior // in this case, replace var uploadProps = new Microsoft.Graph.DriveItemUploadableProperties { ODataType = null, AdditionalData = new Dictionary <string, object> { { "@microsoft.graph.conflictBehavior", "replace" } } }; string itemPath = Path.GetFileName(fileDialog.FileName); // Create the upload session // itemPath does not need to be a path to an existing item var uploadSession = await graphClient.Me.Drive.Root .ItemWithPath(itemPath) .CreateUploadSession(uploadProps) .Request() .PostAsync(); // Max slice size must be a multiple of 320 KiB int maxSliceSize = 10 * 320 * 1024; var fileUploadTask = new Microsoft.Graph.LargeFileUploadTask <Microsoft.Graph.DriveItem>(uploadSession, fileStream, maxSliceSize); // Create a callback that is invoked after each slice is uploaded IProgress <long> progress = new Progress <long>(prog => { ProgressLabel.Content = $"Uploaded {prog} bytes of {fileStream.Length} bytes"; }); try { // Upload the file var uploadResult = await fileUploadTask.UploadAsync(progress); if (uploadResult.UploadSucceeded) { // The ItemResponse object in the result represents the created item. MessageBox.Show($"Added file {uploadResult.ItemResponse.Name} to the signed in user's OneDrive"); } else { MessageBox.Show("Upload failed", "Error"); } } catch (Microsoft.Graph.ServiceException ex) { MessageBox.Show($"Error uploading: {ex} ", "Error"); } ProgressLabel.Content = ""; // Approach for uploading files guaranteed below 4MB in size //var addedItem = await graphClient.Me.Drive.Root.ItemWithPath(Path.GetFileName(fileDialog.FileName)).Content //.Request() //.PutAsync<Microsoft.Graph.DriveItem>(fileStream); //MessageBox.Show($"Added file {addedItem.Name} to the signed in user's OneDrive"); }); } // There is no access token in the cache, so prompt the user to sign-in. catch (MsalUiRequiredException) { MessageBox.Show("Please re-sign"); SignInButton.Content = SignInString; } catch (MsalException ex) { // An unexpected error occurred. string message = ex.Message; if (ex.InnerException != null) { message += "Error Code: " + ex.ErrorCode + "Inner Exception : " + ex.InnerException.Message; } Dispatcher.Invoke(() => { UserName.Content = FilesApplication.Resources.UserNotSignedIn; MessageBox.Show("Unexpected error: " + message); }); return; } } } }
public DriveAccountService(DriveContext siteContext, TokenService tokenService) { SiteContext = siteContext; _app = tokenService.app; Graph = tokenService.Graph; }
public static async Task <Tuple <string, string> > UploadFileToTeamsChannel(string aadAccessToken, string selectedTeamId, string filePath, string pathToItem) { var authHelper = new Utils.O365.AuthenticationHelper() { AccessToken = aadAccessToken }; Microsoft.Graph.GraphServiceClient gcs = new Microsoft.Graph.GraphServiceClient(authHelper); var fileExists = CheckIfFileExistsOnTeamsChannel(aadAccessToken, selectedTeamId, pathToItem); if (fileExists.Item1 != "") { return(new Tuple <string, string>(fileExists.Item1, fileExists.Item2)); } Microsoft.Graph.UploadSession uploadSession = null; uploadSession = await gcs.Groups[selectedTeamId].Drive.Root.ItemWithPath(pathToItem). CreateUploadSession().Request().PostAsync(); try { Console.WriteLine("Trying to upload file to MS Teams SPo Folder " + filePath); using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { //upload a file in a single shot. this is great if all files are below the allowed maximum size for a single shot upload. //however, we're not going to be clever and chunk all files. //{ //var result = await gcs.Groups[selectedTeamId].Drive.Root.ItemWithPath("/" + channelName + "/channelsurf/fileattachments/" + fileId). //Content.Request().PutAsync<Microsoft.Graph.DriveItem>(fs); //} // don't be clever: assume you have to chunk all files, even those below the single shot maximum // credit to https://stackoverflow.com/questions/43974320/maximum-request-length-exceeded-when-uploading-a-file-to-onedrive/43983895 var maxChunkSize = 320 * 1024; // 320 KB - Change this to your chunk size. 5MB is the default. var chunkedUploadProvider = new Microsoft.Graph.ChunkedUploadProvider(uploadSession, gcs, fs, maxChunkSize); var chunkRequests = chunkedUploadProvider.GetUploadChunkRequests(); var readBuffer = new byte[maxChunkSize]; var trackedExceptions = new List <Exception>(); Microsoft.Graph.DriveItem itemResult = null; //upload the chunks foreach (var request in chunkRequests) { var result = await chunkedUploadProvider.GetChunkRequestResponseAsync(request, readBuffer, trackedExceptions); if (result.UploadSucceeded) { itemResult = result.ItemResponse; } } Console.WriteLine("Upload of attachment to MS Teams completed " + pathToItem); Console.WriteLine("SPo ID is " + itemResult.Id); return(new Tuple <string, string>(itemResult.Id, itemResult.WebUrl)); } } catch (Exception ex) { Console.WriteLine("Error: attachment could not be uploaded" + ex.InnerException); } return(new Tuple <string, string>("", "")); }
public async Task <string> GraphTest() { try { // The ClientCredential is where you pass in your client_id and client_secret, which are // provided to Azure AD in order to receive an access_token using the app's identity. var credential = new Microsoft.Identity.Client.ClientCredential(AppConfig.AzureAdOptions.ClientSecret); var cca = new Microsoft.Identity.Client.ConfidentialClientApplication( AppConfig.AzureAdOptions.ClientId, "https://login.microsoftonline.com/nekosoftbtgmail.onmicrosoft.com", $"{AppConfig.WebApplication.BaseUrl.TrimEnd('/')}/{AppConfig.AzureAdOptions.CallbackPath.TrimStart('/')}", credential, null, null); var scopes = "email User.Read User.ReadBasic.All Mail.Send" .Split(' ') .Select(t => ("https://graph.microsoft.com/" + t).ToLower()) .ToArray(); var result = cca.AcquireTokenForClientAsync(new[] { "https://graph.microsoft.com/.default" }).Result; //var result = cca.AcquireTokenForClientAsync(scopes).Result; does not work(?) var graphClient = new Microsoft.Graph.GraphServiceClient(new Microsoft.Graph.DelegateAuthenticationProvider( async requestMessage => { // Passing tenant ID to the sample auth provider to use as a cache key //var accessToken = await _authProvider.GetUserAccessTokenAsync(userId); // Append the access token to the request requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken); // This header identifies the sample in the Microsoft Graph service. If extracting this code for your project please remove. //requestMessage.Headers.Add("SampleID", "aspnetcore-connect-sample"); })); var userId = "d97257fc-15e8-4f06-8384-988e055f72ca"; try { // Load user profile. var users = await graphClient.Users.Request().GetAsync(); //var user = await graphClient.Users[userId].Request().GetAsync(); does not work(?) return(JsonConvert.SerializeObject(users, Formatting.Indented)); } catch (Microsoft.Graph.ServiceException e) { switch (e.Error.Code) { case "Request_ResourceNotFound": case "ResourceNotFound": case "ErrorItemNotFound": case "itemNotFound": return(JsonConvert.SerializeObject(new { Message = $"User '{userId}' was not found." }, Formatting.Indented)); case "ErrorInvalidUser": return(JsonConvert.SerializeObject(new { Message = $"The requested user '{userId}' is invalid." }, Formatting.Indented)); case "AuthenticationFailure": return(JsonConvert.SerializeObject(new { e.Error.Message }, Formatting.Indented)); case "TokenNotFound": //await httpContext.ChallengeAsync(); return(JsonConvert.SerializeObject(new { e.Error.Message }, Formatting.Indented)); default: return(JsonConvert.SerializeObject(new { Message = "An unknown error has occured." }, Formatting.Indented)); } } } catch (Exception ex) { throw ex; } }