public async Task <IEnumerable <IFileSystemItem> > GetMyFiles(int pageIndex, int pageSize) { var client = new SharePointClient(ServiceEndpointUri, GetAccessToken); var filesResults = await client.Files.ExecuteAsync(); return(filesResults.CurrentPage.OrderBy(e => e.Name).Skip(pageIndex * pageSize).Take(pageSize)); }
/// <summary> /// Checks that a SharePoint client is available to the client. /// </summary> /// <returns>The SharePoint Online client.</returns> public static async Task <SharePointClient> EnsureSharePointClientCreatedAsync() { try { AuthenticationContext = new AuthenticationContext(CommonAuthority); if (AuthenticationContext.TokenCache.ReadItems().Count() > 0) { // Bind the AuthenticationContext to the authority that sourced the token in the cache // this is needed for the cache to work when asking for a token from that authority // (the common endpoint never triggers cache hits) string cachedAuthority = AuthenticationContext.TokenCache.ReadItems().First().Authority; AuthenticationContext = new AuthenticationContext(cachedAuthority); } // Create a DiscoveryClient using the discovery endpoint Uri. DiscoveryClient discovery = new DiscoveryClient(DiscoveryServiceEndpointUri, async() => await AcquireTokenAsync(AuthenticationContext, DiscoveryResourceId)); // Now get the capability that you are interested in. CapabilityDiscoveryResult result = await discovery.DiscoverCapabilityAsync("MyFiles"); var client = new SharePointClient( result.ServiceEndpointUri, async() => await AcquireTokenAsync(AuthenticationContext, result.ServiceResourceId)); return(client); } catch (DiscoveryFailedException dfe) { MessageDialogHelper.DisplayException(dfe as Exception); // Discovery failed. AuthenticationContext.TokenCache.Clear(); return(null); } catch (MissingConfigurationValueException mcve) { MessageDialogHelper.DisplayException(mcve); // Connected services not added correctly, or permissions not set correctly. AuthenticationContext.TokenCache.Clear(); return(null); } catch (AuthenticationFailedException afe) { MessageDialogHelper.DisplayException(afe); // Failed to authenticate the user AuthenticationContext.TokenCache.Clear(); return(null); } catch (ArgumentException ae) { MessageDialogHelper.DisplayException(ae as Exception); // Argument exception AuthenticationContext.TokenCache.Clear(); return(null); } }
public async Task Download(string fileId) { if (ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier) == null) { RedirectToAction("", "Home"); } SharePointClient client = await GetSharePointClient(); var file = client.Files.GetById(fileId).ToFile(); using (Stream stream = await file.DownloadAsync()) { using (MemoryStream ms = new MemoryStream()) { stream.Seek(0, SeekOrigin.Begin); stream.CopyTo(ms); byte[] buffer = ms.ToArray(); var fileData = await file.ExecuteAsync(); Response.Clear(); Response.ContentType = GetContentType(fileData.Name); Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileData.Name, System.Text.Encoding.UTF8)); Response.AddHeader("Content-Length", buffer.Length.ToString()); Response.OutputStream.Write(buffer, 0, buffer.Length); Response.Flush(); } } }
public static async Task addFiles(SharePointClient myFilesClient) { FileOpenPicker picker = new FileOpenPicker(); picker.FileTypeFilter.Add("*"); picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary; IReadOnlyList <StorageFile> sFiles = await picker.PickMultipleFilesAsync(); foreach (var sFile in sFiles) { if (sFile != null) { using (var stream = await sFile.OpenStreamForReadAsync()) { File newFile = new File { Name = sFile.Name }; await myFilesClient.Files.AddItemAsync(newFile); await myFilesClient.Files.GetById(newFile.Id).ToFile().UploadAsync(stream); } } } }
/*private string DiscoverPostApiUrl(string baseUrl, string blogPath) * { * * }*/ /// <summary> /// Verifies the user credentials and determines whether SharePoint is configure to use HTTP or MetaWeblog authentication /// </summary> /// <param name="postApiUrl"></param> /// <param name="blogCredentials"></param> /// <param name="credentials"></param> /// <returns></returns> private static bool VerifyCredentialsAndDetectAuthScheme(string postApiUrl, IBlogCredentials blogCredentials, IBlogCredentialsAccessor credentials) { BlogClientAttribute blogClientAttr = (BlogClientAttribute)typeof(SharePointClient).GetCustomAttributes(typeof(BlogClientAttribute), false)[0]; SharePointClient client = (SharePointClient)BlogClientManager.CreateClient(blogClientAttr.TypeName, postApiUrl, credentials); return(SharePointClient.VerifyCredentialsAndDetectAuthScheme(blogCredentials, client)); }
private static async Task<SharePointClient> GetSharePointClient() { string signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; string userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; string tenantId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value; AuthenticationContext authContext = new AuthenticationContext(string.Format("{0}/{1}", SettingsHelper.AuthorizationUri, tenantId), new ADALTokenCache(signInUserId)); DiscoveryClient discovery = new DiscoveryClient(SettingsHelper.DiscoveryServiceEndpointUri, async () => { var authResult = await authContext.AcquireTokenSilentAsync(SettingsHelper.DiscoveryServiceResourceId, new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId)); return authResult.AccessToken; }); CapabilityDiscoveryResult capability = await discovery.DiscoverCapabilityAsync(SettingsHelper.Capability); SharePointClient client = new SharePointClient(capability.ServiceEndpointUri, async () => { var authResult = await authContext.AcquireTokenSilentAsync(capability.ServiceResourceId, new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId)); return authResult.AccessToken; }); return client; }
public override async Task ExecuteAsync() { var id = await SharePointClient.AddItemAsync <TSharePointItem>( SharePointItemTracking.ConfigureReferences(SharePointClient.Tracking)); SharePointItemTracking.Id = id; }
private void UploadDocument(string outputFileName) { SharePointClient spClient = new SharePointClient(); spClient.OverwriteExistingFiles = true; // Set the credentials and proxy if (_serverSettings.UserName != null) { spClient.Credentials = new NetworkCredential(_serverSettings.UserName, _serverSettings.Password, _serverSettings.Domain); } if (_serverSettings.ProxyUri != null) { WebProxy proxy = new WebProxy(_serverSettings.ProxyUri, _serverSettings.ProxyPort); if (proxy.Credentials == null && spClient.Credentials != null) { proxy.Credentials = spClient.Credentials; } else { proxy.Credentials = CredentialCache.DefaultCredentials; } spClient.Proxy = proxy; } else spClient.Proxy = WebRequest.GetSystemWebProxy(); // Get default system proxy settings // Upload the file spClient.UploadFile(outputFileName, new Uri(_serverSettings.Uri), _serverDocumentPathAndFileName); }
public override async Task PrepareAsync() { await SharePointItemTracking.ConfigureUserFieldsAsync(SharePointClient); var item = await SharePointClient.GetAllFieldsByIdAsync<TSharePointFile>(SharePointItemTracking.Id); SharePointItemTracking.LoadOriginalItem(item.Key, item.Value); }
// GET: MyFiles public async Task<ActionResult> Index() { List<MyFile> myFiles = new List<MyFile>(); var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; var tenantId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value; AuthenticationContext authContext = new AuthenticationContext(string.Format(AADAppSettings.AuthorizationUri, tenantId), new ADALTokenCache(signInUserId)); try { DiscoveryClient discClient = new DiscoveryClient(AADAppSettings.DiscoveryServiceEndpointUri, async () => { var authResult = await authContext.AcquireTokenSilentAsync(AADAppSettings.DiscoveryServiceResourceId, new ClientCredential(AADAppSettings.ClientId, AADAppSettings.AppKey), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId)); return authResult.AccessToken; }); var dcr = await discClient.DiscoverCapabilityAsync("MyFiles"); ViewBag.ResourceId = dcr.ServiceResourceId; SharePointClient spClient = new SharePointClient(dcr.ServiceEndpointUri, async () => { var authResult = await authContext.AcquireTokenSilentAsync(dcr.ServiceResourceId, new ClientCredential(AADAppSettings.ClientId, AADAppSettings.AppKey), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId)); return authResult.AccessToken; }); var filesResult = await spClient.Files.ExecuteAsync(); do { var files = filesResult.CurrentPage.OfType<File>(); foreach (var file in files) { myFiles.Add(new MyFile { Name = file.Name }); } filesResult = await filesResult.GetNextPageAsync(); } while (filesResult != null); } catch (AdalException exception) { //handle token acquisition failure if (exception.ErrorCode == AdalError.FailedToAcquireTokenSilently) { authContext.TokenCache.Clear(); ViewBag.ErrorMessage = "AuthorizationRequired"; } } return View(myFiles); }
public async Task DeleteFile(string id) { var client = new SharePointClient(ServiceEndpointUri, GetAccessToken); IFileSystemItem fileSystemItem = await client.Files.GetByIdAsync(id); await fileSystemItem.DeleteAsync(); }
private static async Task <SharePointClient> GetSharePointClient() { string signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; string userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; string tenantId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value; AuthenticationContext authContext = new AuthenticationContext(string.Format("{0}/{1}", SettingsHelper.AuthorizationUri, tenantId), new ADALTokenCache(signInUserId)); DiscoveryClient discovery = new DiscoveryClient(SettingsHelper.DiscoveryServiceEndpointUri, async() => { var authResult = await authContext.AcquireTokenSilentAsync(SettingsHelper.DiscoveryServiceResourceId, new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId)); return(authResult.AccessToken); }); CapabilityDiscoveryResult capability = await discovery.DiscoverCapabilityAsync(SettingsHelper.Capability); SharePointClient client = new SharePointClient(capability.ServiceEndpointUri, async() => { var authResult = await authContext.AcquireTokenSilentAsync(capability.ServiceResourceId, new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId)); return(authResult.AccessToken); }); return(client); }
private async void btnGetMyFiles_Click(object sender, RoutedEventArgs e) { Files.Clear(); DiscoveryClient discoveryClient = new DiscoveryClient( async() => { var authResult = await AuthenticationHelper.GetAccessToken(AuthenticationHelper.DiscoveryServiceResourceId); return(authResult.AccessToken); } ); var appCapabilities = await discoveryClient.DiscoverCapabilitiesAsync(); var myFilesCapability = appCapabilities .Where(s => s.Key == "MyFiles") .Select(p => new { Key = p.Key, ServiceResourceId = p.Value.ServiceResourceId, ServiceEndPointUri = p.Value.ServiceEndpointUri }) .FirstOrDefault(); if (myFilesCapability != null) { SharePointClient myFilesClient = new SharePointClient(myFilesCapability.ServiceEndPointUri, async() => { var authResult = await AuthenticationHelper.GetAccessToken(myFilesCapability.ServiceResourceId); return(authResult.AccessToken); }); var myFilesResult = await myFilesClient.Files.ExecuteAsync(); do { var myFiles = myFilesResult.CurrentPage; foreach (var myFile in myFiles) { Files.Add(new MyFile { Name = myFile.Name }); } myFilesResult = await myFilesResult.GetNextPageAsync(); } while (myFilesResult != null); if (Files.Count == 0) { Files.Add(new MyFile { Name = "No files to display!" }); } } else { MessageDialog dialog = new MessageDialog(string.Format("This Windows app does not have access to users' files. Please contact your administrator.")); await dialog.ShowAsync(); } }
public async Task <JsonResult> List(string folderId) { if (ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier) == null) { return(Json(new { success = false, message = "Authentication Required" })); } List <OneDriveItemViewModel> oneDriveItems = new List <OneDriveItemViewModel>(); try { SharePointClient client = await GetSharePointClient(); if (string.IsNullOrEmpty(folderId)) { var filesResult = await client.Files.ExecuteAsync(); do { var files = filesResult.CurrentPage; foreach (var file in files) { string extension = (file.Type == "File") ? System.IO.Path.GetExtension(file.Name).Split('.')[1] : string.Empty; oneDriveItems.Add(new OneDriveItemViewModel { Id = file.Id, Name = file.Name, Size = file.Size, Type = file.Type, Extension = extension, Creator = file.CreatedBy.User.DisplayName }); } filesResult = filesResult.GetNextPageAsync().GetAwaiter().GetResult(); } while (filesResult != null); } else { var filesResult = await client.Files.GetById(folderId).ToFolder().Children.ExecuteAsync(); do { var files = filesResult.CurrentPage; foreach (var file in files) { string extension = (file.Type == "File") ? System.IO.Path.GetExtension(file.Name).Split('.')[1] : string.Empty; oneDriveItems.Add(new OneDriveItemViewModel { Id = file.Id, Name = file.Name, Size = file.Size, Type = file.Type, Extension = extension, Creator = file.CreatedBy.User.DisplayName }); } filesResult = filesResult.GetNextPageAsync().GetAwaiter().GetResult(); } while (filesResult != null); } } catch (AdalException exception) { //handle token acquisition failure return(Json(new { success = false, message = "Authorization Required" })); } catch { return(Json(new { success = false, message = "Unexpected exception" })); } return(Json(new { success = true, items = oneDriveItems.OrderBy(x => x.Type).OrderBy(x => x.Name) })); }
public override async Task UndoAsync() { if (SharePointItemTracking.Id > 0) { await SharePointClient.DeleteItemAsync <TSharePointItem>(SharePointItemTracking.Id); } SharePointItemTracking.Id = 0; }
public void Init() { var settings = Settings.SharePointPrd; var auth = new XAuth.Auth(settings.Auth); client = new SharePointClient(settings.Environment.EndpointUri, () => auth.GetAccessToken(settings.Environment.ResourceId)); }
public override async Task UndoAsync() { var sharePointFile = (ISharePointFile)SharePointItemTracking.OriginalItem; await SharePointClient.AddFileAsync<TSharePointFile>( SharePointItemTracking.ConfigureReferences(SharePointClient.Tracking, true), sharePointFile.FileName, sharePointFile.Folder, sharePointFile.InputStream, true); }
public override async Task UndoAsync() { var sharePointFile = (ISharePointFile)SharePointItemTracking.OriginalItem; await SharePointClient.AddFileAsync <TSharePointFile>( SharePointItemTracking.OriginalFields.ToDictionary(), sharePointFile.FileName, sharePointFile.Folder, sharePointFile.InputStream, false); }
public static async Task <ICollection <OneDriveFile> > GetFilesAsync(SharePointClient client) { var filesResults = await client.Files.ExecuteAsync(); return(filesResults.CurrentPage.Select(file => new OneDriveFile() { Name = file.Name, WebUrl = file.WebUrl, SourceId = file.Id }).ToList()); }
// GET: Files public async Task <ActionResult> Index() { List <MyFile> myFiles = new List <MyFile>(); var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.Authority, new ADALTokenCache(signInUserId)); try { DiscoveryClient discClient = new DiscoveryClient(SettingsHelper.DiscoveryServiceEndpointUri, async() => { var authResult = await authContext.AcquireTokenSilentAsync(SettingsHelper.DiscoveryServiceResourceId, new ClientCredential(SettingsHelper.ClientId, SettingsHelper.AppKey), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId)); return(authResult.AccessToken); }); var dcr = await discClient.DiscoverCapabilityAsync("MyFiles"); SharePointClient exClient = new SharePointClient(dcr.ServiceEndpointUri, async() => { var authResult = await authContext.AcquireTokenSilentAsync(dcr.ServiceResourceId, new ClientCredential(SettingsHelper.ClientId, SettingsHelper.AppKey), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId)); return(authResult.AccessToken); }); var filesResult = await exClient.Files.ExecuteAsync(); do { var files = filesResult.CurrentPage; foreach (var file in files) { myFiles.Add(new MyFile { Name = file.Name }); } filesResult = await filesResult.GetNextPageAsync(); } while (filesResult != null); } catch (AdalException exception) { //handle token acquisition failure if (exception.ErrorCode == AdalError.FailedToAcquireTokenSilently) { authContext.TokenCache.Clear(); //handle token acquisition failure } } return(View(myFiles)); }
private async Task EnsureClientCreated() { var authenticator = new Authenticator(); var result = await authenticator.AuthenticateAsync("MyFiles", ServiceIdentifierKind.Capability); // Create a client proxy: this.client = new SharePointClient(result.ServiceUri, result.GetAccessToken); this.client.Context.IgnoreMissingProperties = true; }
public override async Task UndoAsync() { if (SharePointItemTracking.Id > 0) { await SharePointClient.DeleteFileAsync <TSharePointFile>(SharePointItemTracking.Id); await SharePointClient.RemoveFoldersAsync <TSharePointFile>(_createdFolders); } SharePointItemTracking.Id = 0; }
static void Main(string[] args) { var client = new SharePointClient( new Uri("https://microsoft320-my.sharepoint.com/_api/v2.0/"), () => { return(Task.FromResult("eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik1uQ19WWmNBVGZNNXBPWWlKSE1iYTlnb0VLWSIsImtpZCI6Ik1uQ19WWmNBVGZNNXBPWWlKSE1iYTlnb0VLWSJ9.eyJhdWQiOiJodHRwczovL21pY3Jvc29mdDMyMC1teS5zaGFyZXBvaW50LmNvbS8iLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC9lMDdkMjIwZS1mNGMyLTQ0MWYtYWQ5YS05ZDZmYTU5YjRlNTIvIiwiaWF0IjoxNDU5MTY0ODI0LCJuYmYiOjE0NTkxNjQ4MjQsImV4cCI6MTQ1OTE2ODcyNCwiYWNyIjoiMSIsImFtciI6WyJwd2QiXSwiYXBwaWQiOiIyNGJiMTcyNS01NGQ5LTQxOTAtYjU4Yy1iYTUzNDdmYjMzNmUiLCJhcHBpZGFjciI6IjAiLCJmYW1pbHlfbmFtZSI6IkplZmZyZXkiLCJnaXZlbl9uYW1lIjoiQ2hlbiIsImlwYWRkciI6IjE2Ny4yMjAuMjMyLjUxIiwibmFtZSI6IkplZmZyZXkgQ2hlbiIsIm9pZCI6IjEyYmEwNzIwLTg0ZGEtNDZjMy05N2U1LWQ0YWU3YWNkNDMzMyIsInB1aWQiOiIxMDAzQkZGRDg3Njk1OUQyIiwic2NwIjoiQ2FsZW5kYXJzLlJlYWQgTWFpbC5SZWFkIE1haWwuU2VuZCBNeUZpbGVzLlJlYWQgTXlGaWxlcy5Xcml0ZSBvcGVuaWQiLCJzdWIiOiI3Uk9TZmluVzl0U1o5bDdZcEJpNFdrUWFHR3pKb2E0NURFUHFSaVhtTS1vIiwidGlkIjoiZTA3ZDIyMGUtZjRjMi00NDFmLWFkOWEtOWQ2ZmE1OWI0ZTUyIiwidW5pcXVlX25hbWUiOiJqZWNATWljcm9zb2Z0MzIwLm9ubWljcm9zb2Z0LmNvbSIsInVwbiI6ImplY0BNaWNyb3NvZnQzMjAub25taWNyb3NvZnQuY29tIiwidmVyIjoiMS4wIn0.d_VlBeQWsk4_FNLq6_MzgOY5OMDVT8yA9t8JcyqLJwqknJJR4zQ7Ntfu_lDcptIHpD0H8CsuNmL08xLneUEaDEFhYvIuDeJ_0rbetvnHRgHW9YWr6leWvXyWvosgCFl6jC85kppAOOpsYphZiLtLFYjUODMB1OeW2FW7YXxKSW2D2nn7O3SAkOMM62Eh30bFXUu5-lP2TbaZrsm8HZ6DLLsQYOQ-CS5wIkM4N7u_giwBBgmE3AliZ6klYec5OvwBWSyS9pjUlL3tN33cg6YwvqLg4LBsQcgGea5NwXch_DynzGQcOtfrYHrA08xGwUPKxMiGQ2Ge3vtCTUNeIqdQtw")); }); client.Files.GetById("");; var drive = client.Drive.ExecuteAsync().Result; }
/// <summary> /// Checks that a SharePoint client is available to the client. /// </summary> /// <returns>The SharePoint Online client.</returns> public static async Task <SharePointClient> EnsureSharePointClientCreatedAsync() { //Check to see if this client has already been created. If so, return it. Otherwise, create a new one. if (_sharePointClient != null) { return(_sharePointClient); } else { try { // Now get the capability that you are interested in. CapabilityDiscoveryResult result = await GetDiscoveryCapabilityResultAsync("MyFiles"); _sharePointClient = new SharePointClient( result.ServiceEndpointUri, async() => await GetTokenHelperAsync(_authenticationContext, result.ServiceResourceId)); return(_sharePointClient); } catch (DiscoveryFailedException dfe) { MessageDialogHelper.DisplayException(dfe as Exception); // Discovery failed. _authenticationContext.TokenCache.Clear(); return(null); } catch (MissingConfigurationValueException mcve) { MessageDialogHelper.DisplayException(mcve); // Connected services not added correctly, or permissions not set correctly. _authenticationContext.TokenCache.Clear(); return(null); } catch (AuthenticationFailedException afe) { MessageDialogHelper.DisplayException(afe); // Failed to authenticate the user _authenticationContext.TokenCache.Clear(); return(null); } catch (ArgumentException ae) { MessageDialogHelper.DisplayException(ae as Exception); // Argument exception _authenticationContext.TokenCache.Clear(); return(null); } } }
protected virtual void Dispose(bool disposing) { if (Disposed) { return; } if (disposing) { SharePointClient?.Dispose(); } Disposed = true; }
public static async Task<List<IItem>> getMyFiles(SharePointClient spClient) { List<IItem> myFilesList = new List<IItem>(); var myFilesResult = await spClient.Files.ExecuteAsync(); do { var files = myFilesResult.CurrentPage; foreach (var file in files) { myFilesList.Add(file); } myFilesResult = await myFilesResult.GetNextPageAsync(); } while (myFilesResult != null); return myFilesList; }
private async Task RunAsync(CancellationToken cancellationToken) { SharePointClient sharepointClient = new SharePointClient(); while (!cancellationToken.IsCancellationRequested) { var complaints = await sharepointClient.GetComplaints(); Trace.TraceInformation($"Getting {complaints.Count} complaints"); EnQueueMessage(); await Task.Delay(60000); } }
public static async Task <List <IItem> > getMyFiles(SharePointClient myFilesClient) { List <IItem> myFiles = new List <IItem>(); var myFilesResult = await myFilesClient.Files.ExecuteAsync(); do { var files = myFilesResult.CurrentPage; foreach (var myFile in files) { myFiles.Add(myFile); } myFilesResult = await myFilesResult.GetNextPageAsync(); } while (myFilesResult != null); return(myFiles); }
public static SharePointClient ensureSharepointClientCreated(IDictionary <string, CapabilityDiscoveryResult> appCapabilities, string capability) { var contactsCapability = appCapabilities .Where(s => s.Key == capability) .Select(p => new { Key = p.Key, ServiceResourceId = p.Value.ServiceResourceId, ServiceEndPointUri = p.Value.ServiceEndpointUri }) .FirstOrDefault(); SharePointClient spClient = new SharePointClient(contactsCapability.ServiceEndPointUri, async() => { var authResult = await AuthenticationHelper.GetAccessToken(contactsCapability.ServiceResourceId); return(authResult.AccessToken); }); return(spClient); }
public static SharePointClient ensureSPClientCreated(IDictionary<string, CapabilityDiscoveryResult> appCapabilities, string capability) { var myFilesCapability = appCapabilities .Where(s => s.Key == capability) .Select(p => new { Key = p.Key, ServiceResourceId = p.Value.ServiceResourceId, ServiceEndPointUri = p.Value.ServiceEndpointUri }) .FirstOrDefault(); SharePointClient spClient = new SharePointClient(myFilesCapability.ServiceEndPointUri, async () => { var authResult = await AuthenticationHelper.GetAccessToken(myFilesCapability.ServiceResourceId); return authResult.AccessToken; }); return spClient; }
/// <summary> /// Signs the user out of the service. /// </summary> public static async Task SignOutAsync() { if (string.IsNullOrEmpty(LoggedInUser)) { return; } _authenticationContext.TokenCache.Clear(); //Clean up all existing clients _graphClient = null; _outlookClient = null; _sharePointClient = null; //Clear stored values from last authentication. Leave value for LoggedInUser so that we can try again if logout fails. _settings.Values["TenantId"] = null; _settings.Values["LastAuthority"] = null; }
private void TryDownload() { _mainForm.SetOperationText("Downloading " + _tryDownloadItem.AbsoluteUri); Exception error = null; // Download the file try { SharePointClient spClient = new SharePointClient(); // Set the credentials and proxy if (_serverSettings.UserName != null) { spClient.Credentials = new NetworkCredential(_serverSettings.UserName, _serverSettings.Password, _serverSettings.Domain); } if (_serverSettings.ProxyUri != null) { WebProxy proxy = new WebProxy(_serverSettings.ProxyUri, _serverSettings.ProxyPort); if (proxy.Credentials == null && spClient.Credentials != null) { proxy.Credentials = spClient.Credentials; } else { proxy.Credentials = CredentialCache.DefaultCredentials; } spClient.Proxy = proxy; } else { spClient.Proxy = WebRequest.GetSystemWebProxy(); // Get default system proxy settings } // Download the file spClient.DownloadFile(_tryDownloadItem.AbsoluteUri, _tryDownloadFileName); System.Diagnostics.Process.Start(_tryDownloadFileName); } catch (Exception ex) { error = ex; } _mainForm.EndOperation(error); }
/// <summary> /// Class initialization. /// </summary> /// <param name="client"></param> /// <param name="baseAddress"></param> /// <param name="dtoResolver"></param> /// <param name="mapper"></param> private void Setup(HttpClient client, Uri baseAddress, IDataTransferObjectResolver dtoResolver, IMapper mapper) { _httpClient = client; _baseAddress = baseAddress; _dtoResolver = dtoResolver; _mapper = mapper; BackupRepositories = new BackupRepositoryClient(this); Jobs = new JobClient(this); Mailboxes = new MailboxClient(this); OneDrives = new OneDriveClient(this); Organizations = new OrganizationClient(this); OrganizationUsers = new OrganizationUserClient(this); OrganizationSites = new OrganizationSiteClient(this); OrganizationGroups = new OrganizationGroupClient(this); SharePoints = new SharePointClient(this); RestoreSessions = new RestoreSessionClient(this); LicensedUsers = new LicensedUserClient(this); }
public async Task Upload() { if (ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier) == null) { //not authenticated RedirectToAction("", "Home"); } var length = Request.ContentLength; if (length > 0) { SharePointClient client = await GetSharePointClient(); var fileName = Request.Headers["X-File-Name"]; try { // First check if a file with the same name already exists. If it exists, delete it. var item = await client.Files.GetByPathAsync(fileName); await item.DeleteAsync(); } catch { //there is no file with the same name, swallow the error and continue } var oneDriveFile = new Microsoft.Office365.SharePoint.FileServices.File { Name = fileName }; await client.Files.AddItemAsync(oneDriveFile); await client.Files.GetById(oneDriveFile.Id).ToFile().UploadAsync(Request.InputStream); } else { throw new Exception("Empty piece"); } }
public static async Task<ICollection<OneDriveFile>> GetFilesAsync(SharePointClient client) { var filesResults = await client.Files.ExecuteAsync(); return filesResults.CurrentPage.Select(file => new OneDriveFile() { Name = file.Name, WebUrl = file.WebUrl, SourceId = file.Id }).ToList(); }
// GET: Files public async Task<ActionResult> Index(string authError) { List<MyFile> myFiles = new List<MyFile>(); AuthenticationContext authContext = null; AuthenticationResult result = null; CapabilityDiscoveryResult filesCapabilityDiscoveryResult = null; DiscoveryClient discoveryClient = null; SharePointClient spClient = null; string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier").Value; ClientCredential credential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.AppKey); try { authContext = new AuthenticationContext(SettingsHelper.Authority, new TokenDbCache(userObjectID)); if (authError != null) { Uri redirectUri = new Uri(Request.Url.GetLeftPart(UriPartial.Authority).ToString() + "/OAuth"); string state = GenerateState(userObjectID, Request.Url.ToString()); ViewBag.AuthorizationUrl = authContext.GetAuthorizationRequestURL(SettingsHelper.DiscoveryServiceResourceId, SettingsHelper.ClientId, redirectUri, UserIdentifier.AnyUser, state == null ? null : "&state=" + state); ViewBag.ErrorMessage = "UnexpectedError"; return View(myFiles); } // Query Discovery Service to retrieve MyFiles capability result result = authContext.AcquireTokenSilent(SettingsHelper.DiscoveryServiceResourceId, credential, UserIdentifier.AnyUser); discoveryClient = new DiscoveryClient(() => { return result.AccessToken; }); } catch (AdalException e) { if (e.ErrorCode == AdalError.FailedToAcquireTokenSilently) { // The user needs to re-authorize. Show them a message to that effect. // If the user still has a valid session with Azure AD, they will not be prompted for their credentials. ViewBag.ErrorMessage = "AuthorizationRequired"; authContext = new AuthenticationContext(SettingsHelper.Authority); Uri redirectUri = new Uri(Request.Url.GetLeftPart(UriPartial.Authority).ToString() + "/OAuth"); string state = GenerateState(userObjectID, Request.Url.ToString()); ViewBag.AuthorizationUrl = authContext.GetAuthorizationRequestURL(SettingsHelper.DiscoveryServiceResourceId, SettingsHelper.ClientId, redirectUri, UserIdentifier.AnyUser, state == null ? null : "&state=" + state); return View(myFiles); } ViewBag.ErrorMessage = "Error while Acquiring Token from Cache."; return View("Error"); } try { ViewBag.Office365User = result.UserInfo.GivenName; ActiveDirectoryClient adGraphClient = new ActiveDirectoryClient(SettingsHelper.AADGraphServiceEndpointUri, async () => { var authResult = await authContext.AcquireTokenSilentAsync(SettingsHelper.AADGraphResourceId, credential, UserIdentifier.AnyUser); return authResult.AccessToken; }); var currentUser = await adGraphClient.Users.Where(u => u.ObjectId == result.UserInfo.UniqueId).ExecuteSingleAsync(); ViewBag.Office365User = String.Format("{0} ({1})",currentUser.DisplayName,currentUser.Mail); filesCapabilityDiscoveryResult = await discoveryClient.DiscoverCapabilityAsync("MyFiles"); // Initialize SharePoint client to query users' files spClient = new SharePointClient(filesCapabilityDiscoveryResult.ServiceEndpointUri, async () => { var authResult = await authContext.AcquireTokenSilentAsync(filesCapabilityDiscoveryResult.ServiceResourceId, credential, UserIdentifier.AnyUser); return authResult.AccessToken; }); // Query users' files and get the first paged collection var filesCollection = await spClient.Files.ExecuteAsync(); var files = filesCollection.CurrentPage; foreach (var file in files) { myFiles.Add(new MyFile { Name = file.Name }); } return View(myFiles); } catch (Exception e) { ViewBag.ErrorMessage = String.Format("UnexpectedError: {0}", e.Message); return View("Error"); } }
private async void btnGetMyFiles_Click(object sender, RoutedEventArgs e) { Files.Clear(); DiscoveryClient discoveryClient = new DiscoveryClient( async ()=> { var authResult = await AuthenticationHelper.GetAccessToken(AuthenticationHelper.DiscoveryServiceResourceId); return authResult.AccessToken; } ); var appCapabilities = await discoveryClient.DiscoverCapabilitiesAsync(); var myFilesCapability = appCapabilities .Where(s => s.Key == "MyFiles") .Select(p=>new {Key=p.Key, ServiceResourceId=p.Value.ServiceResourceId, ServiceEndPointUri=p.Value.ServiceEndpointUri}) .FirstOrDefault(); if(myFilesCapability != null) { SharePointClient myFilesClient = new SharePointClient(myFilesCapability.ServiceEndPointUri, async()=> { var authResult = await AuthenticationHelper.GetAccessToken(myFilesCapability.ServiceResourceId); return authResult.AccessToken; }); var myFilesResult = await myFilesClient.Files.ExecuteAsync(); do { var myFiles = myFilesResult.CurrentPage; foreach (var myFile in myFiles) { Files.Add(new MyFile { Name = myFile.Name }); } myFilesResult = await myFilesResult.GetNextPageAsync(); } while (myFilesResult != null); if(Files.Count == 0) { Files.Add(new MyFile { Name = "No files to display!" }); } } else { MessageDialog dialog = new MessageDialog(string.Format("This Windows app does not have access to users' files. Please contact your administrator.")); await dialog.ShowAsync(); } }
/// <summary> /// Checks that a SharePoint client is available to the client. /// </summary> /// <returns>The SharePoint Online client.</returns> public static async Task<SharePointClient> GetSharePointClientAsync(string capability) { //Check to see if this client has already been created. If so, return it. Otherwise, create a new one. if (_sharePointClient != null) { return _sharePointClient; } else { try { // Now get the capability that you are interested in. CapabilityDiscoveryResult result = await GetDiscoveryCapabilityResultAsync(capability); _sharePointClient = new SharePointClient( result.ServiceEndpointUri, async () => await GetTokenHelperAsync(_authenticationContext, result.ServiceResourceId)); return _sharePointClient; } catch (DiscoveryFailedException dfe) { MessageDialogHelper.DisplayException(dfe as Exception); // Discovery failed. _authenticationContext.TokenCache.Clear(); return null; } catch (MissingConfigurationValueException mcve) { MessageDialogHelper.DisplayException(mcve); // Connected services not added correctly, or permissions not set correctly. _authenticationContext.TokenCache.Clear(); return null; } catch (AuthenticationFailedException afe) { MessageDialogHelper.DisplayException(afe); // Failed to authenticate the user _authenticationContext.TokenCache.Clear(); return null; } catch (ArgumentException ae) { MessageDialogHelper.DisplayException(ae as Exception); // Argument exception _authenticationContext.TokenCache.Clear(); return null; } } }
/// <summary> /// Checks that a SharePoint client is available to the client. /// </summary> /// <returns>The SharePoint Online client.</returns> public static async Task<SharePointClient> EnsureSharePointClientCreatedAsync() { try { AuthenticationContext = new AuthenticationContext(CommonAuthority); if (AuthenticationContext.TokenCache.ReadItems().Count() > 0) { // Bind the AuthenticationContext to the authority that sourced the token in the cache // this is needed for the cache to work when asking for a token from that authority // (the common endpoint never triggers cache hits) string cachedAuthority = AuthenticationContext.TokenCache.ReadItems().First().Authority; AuthenticationContext = new AuthenticationContext(cachedAuthority); } // Create a DiscoveryClient using the discovery endpoint Uri. DiscoveryClient discovery = new DiscoveryClient(DiscoveryServiceEndpointUri, async () => await AcquireTokenAsync(AuthenticationContext, DiscoveryResourceId)); // Now get the capability that you are interested in. CapabilityDiscoveryResult result = await discovery.DiscoverCapabilityAsync("MyFiles"); var client = new SharePointClient( result.ServiceEndpointUri, async () => await AcquireTokenAsync(AuthenticationContext, result.ServiceResourceId)); return client; } catch (DiscoveryFailedException dfe) { MessageDialogHelper.DisplayException(dfe as Exception); // Discovery failed. AuthenticationContext.TokenCache.Clear(); return null; } catch (MissingConfigurationValueException mcve) { MessageDialogHelper.DisplayException(mcve); // Connected services not added correctly, or permissions not set correctly. AuthenticationContext.TokenCache.Clear(); return null; } catch (AuthenticationFailedException afe) { MessageDialogHelper.DisplayException(afe); // Failed to authenticate the user AuthenticationContext.TokenCache.Clear(); return null; } catch (ArgumentException ae) { MessageDialogHelper.DisplayException(ae as Exception); // Argument exception AuthenticationContext.TokenCache.Clear(); return null; } }
/// <summary> /// Use the SharePointClient to get OneDrive for Business Files /// </summary> /// <param name="code">The authorization code to use when getting an access token</param> /// <returns></returns> public async Task<ActionResult> Files(string code) { AuthenticationContext authContext = new AuthenticationContext( ConfigurationManager.AppSettings["ida:AuthorizationUri"] + "/common", true); ClientCredential creds = new ClientCredential( ConfigurationManager.AppSettings["ida:ClientID"], ConfigurationManager.AppSettings["ida:Password"]); //Get the discovery information that was saved earlier CapabilityDiscoveryResult cdr = Helpers.GetFromCache("FilesDiscoveryResult") as CapabilityDiscoveryResult; //Get a client, if this page was already visited SharePointClient sharepointClient = Helpers.GetFromCache("SharePointClient") as SharePointClient; //Get an authorization code, if needed if (sharepointClient == null && cdr != null && code == null) { Uri redirectUri = authContext.GetAuthorizationRequestURL( cdr.ServiceResourceId, creds.ClientId, new Uri(Request.Url.AbsoluteUri.Split('?')[0]), UserIdentifier.AnyUser, string.Empty); return Redirect(redirectUri.ToString()); } //Create the SharePointClient if (sharepointClient == null && cdr != null && code != null) { sharepointClient = new SharePointClient(cdr.ServiceEndpointUri, async () => { var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync( code, new Uri(Request.Url.AbsoluteUri.Split('?')[0]), creds); return authResult.AccessToken; }); Helpers.SaveInCache("SharePointClient", sharepointClient); } //Get the files var filesResults = await sharepointClient.Files.ExecuteAsync(); var fileList = new List<MyFile>(); foreach (var file in filesResults.CurrentPage.Where(f => f.Name != "Shared with Everyone").OrderBy(e => e.Name)) { fileList.Add(new MyFile { Id = file.Id, Name = file.Name, Url = file.WebUrl }); } //Save the files Helpers.SaveInCache("FileList", fileList); //Show the files return View(fileList); }
/// <summary> /// Checks that an OutlookServicesClient object is available. /// </summary> /// <returns>The OutlookServicesClient object. </returns> public static async Task<SharePointClient> GetSharePointClientAsync() { if (_sharePointClient != null && !String.IsNullOrEmpty(AuthenticationHelper.LastAuthority)) { Debug.WriteLine("Got a SharePoint client for Files."); return _sharePointClient; } else { try { //First, look for the authority used during the last authentication. //If that value is not populated, use CommonAuthority. string authority = null; if (String.IsNullOrEmpty(AuthenticationHelper.LastAuthority)) { authority = AuthenticationHelper.CommonAuthority; } else { authority = AuthenticationHelper.LastAuthority; } // Create an AuthenticationContext using this authority. AuthenticationHelper._authenticationContext = new AuthenticationContext(authority); // Set the value of _authenticationContext.UseCorporateNetwork to true so that you // can use this app inside a corporate intranet. If the value of UseCorporateNetwork // is true, you also need to add the Enterprise Authentication, Private Networks, and // Shared User Certificates capabilities in the Package.appxmanifest file. AuthenticationHelper._authenticationContext.UseCorporateNetwork = true; //See the Discovery Service Sample (https://github.com/OfficeDev/Office365-Discovery-Service-Sample) //for an approach that improves performance by storing the discovery service information in a cache. DiscoveryClient discoveryClient = new DiscoveryClient( async () => await AuthenticationHelper.GetTokenHelperAsync(AuthenticationHelper._authenticationContext, AuthenticationHelper.DiscoveryResourceId)); // Get the specified capability ("Calendar"). CapabilityDiscoveryResult result = await discoveryClient.DiscoverCapabilityAsync("MyFiles"); var token = await AuthenticationHelper.GetTokenHelperAsync(AuthenticationHelper._authenticationContext, result.ServiceResourceId); // Check the token if (String.IsNullOrEmpty(token)) { // User cancelled sign-in return null; } else { _sharePointClient = new SharePointClient( result.ServiceEndpointUri, async () => await AuthenticationHelper.GetTokenHelperAsync(AuthenticationHelper._authenticationContext, result.ServiceResourceId)); Debug.WriteLine("Got a SharePoint client for Files."); return _sharePointClient; } } // The following is a list of exceptions you should consider handling in your app. // In the case of this sample, the exceptions are handled by returning null upstream. catch (DiscoveryFailedException dfe) { Debug.WriteLine(dfe.Message); } catch (ArgumentException ae) { Debug.WriteLine(ae.Message); } AuthenticationHelper._authenticationContext.TokenCache.Clear(); return null; } }