public object Resolve(object source, Dictionary <String, IResolver> resolvers = null, Boolean recursive = false) { var result = new DriveRootFolder(); var driveItems = source.GetPublicInstancePropertyValue("DriveItems") ?? source.GetPublicInstancePropertyValue("Items"); var driveFolderTypeName = $"{PnPSerializationScope.Current?.BaseSchemaNamespace}.DriveFolder, {PnPSerializationScope.Current?.BaseSchemaAssemblyName}"; var driveFolderType = Type.GetType(driveFolderTypeName, true); var driveFileTypeName = $"{PnPSerializationScope.Current?.BaseSchemaNamespace}.DriveFile, {PnPSerializationScope.Current?.BaseSchemaAssemblyName}"; var driveFileType = Type.GetType(driveFileTypeName, true); if (null != driveItems) { foreach (var d in ((IEnumerable)driveItems)) { if (driveFolderType.IsInstanceOfType(d)) { // If the item is a Folder var targetItem = new DriveFolder(); PnPObjectsMapper.MapProperties(d, targetItem, resolvers, recursive); result.DriveFolders.Add(targetItem); } else if (driveFileType.IsInstanceOfType(d)) { // Else if the item is a File var targetItem = new DriveFile(); PnPObjectsMapper.MapProperties(d, targetItem, resolvers, recursive); result.DriveFiles.Add(targetItem); } } } return(result); }
/// <summary> /// Executes the clipboard operation /// </summary> /// <param name="targetFolder">The target folder of the operation</param> /// <returns>A task representing the operation</returns> public async Task <DriveItem> PasteAsync(DriveFolder targetFolder) { var task = ClipBoard.ExecuteAsync(targetFolder); ClipBoard.Clear(); return(await task); }
public async Task <DriveItem> ExecuteAsync(DriveFolder targetFolder) { if (!CanExecute) { return(null); } return(await Operation.ExecuteAsync(Content, targetFolder)); }
/// <summary> /// Uploads a file with the given name and the given content to the current folder /// </summary> /// <param name="parent">The parent folder of the new file</param> /// <param name="filename">The name of the newly created file</param> /// <param name="file">The StorageFile to be uploaded</param> /// <param name="isRetrying">Determines if the method is retrying after an unauthorized response</param> /// <returns>The uploaded file</returns> public async Task <DriveFile> UploadAsync(DriveFolder parent, string filename, StorageFile file, bool isRetrying = false) { using (var client = new HttpClient()) { var url = new Url(BaseUrl) .AppendPathSegments("items", $"{parent.Id}:", $"{filename}:", "createUploadSession"); var request = new HttpRequestMessage(HttpMethod.Post, url.ToUri()); request.Headers.Authorization = AuthService.Instance.CreateAuthenticationHeader(); // Starting the download session var response = await Task.Run(() => client.SendAsync(request)); if (response.IsSuccessStatusCode) { var obj = JObject.Parse(await response.Content.ReadAsStringAsync()); var uploadUrl = obj["uploadUrl"].ToString(); // Opening an input stream so the whole file does not need to be loaded into the memory using (var stream = await file.OpenStreamForReadAsync()) { // Calculating the amount of chunks to be sent var intermediateChunks = stream.Length % ChunkSize == 0 ? stream.Length / ChunkSize - 1 : stream.Length / ChunkSize; // Sending all the intermediate chunks int i; for (i = 0; i < intermediateChunks; i++) { var bytes = new byte[ChunkSize]; // Reading 60 MB from the file (Chunk size) await stream.ReadAsync(bytes, i *ChunkSize, ChunkSize); // Sending the chunk await SendChunkAsync(client, uploadUrl, bytes, i, stream.Length); } var lastBytes = new byte[stream.Length - i * ChunkSize]; // Reading the remaining bytes from the file await stream.ReadAsync(lastBytes, i *ChunkSize, (int)stream.Length - i *ChunkSize); // Sending the last chunk and returning its result return(await SendLastChunkAsync(client, uploadUrl, lastBytes, i, stream.Length)); } } if (response.StatusCode == HttpStatusCode.Unauthorized && !isRetrying) { await AuthService.Instance.LoginAsync(); return(await UploadAsync(parent, filename, file, true)); } throw new WebException(await response.Content.ReadAsStringAsync()); } }
/// <summary> /// Executes a copy operation awaits it and reloads the target folder into the cache. /// </summary> /// <param name="content">The item to be moved into the folder</param> /// <param name="target">The target folder</param> /// <param name="isRetrying">Determines if the method is retrying after an unauthorized response</param> /// <exception cref="TaskCanceledException">Throws exception upon canceling the monitoring task</exception> /// <returns>The pasted item</returns> public async Task <DriveItem> ExecuteAsync(DriveItem content, DriveFolder target, bool isRetrying) { using (var client = new HttpClient()) { var url = new Url(DriveService.BaseUrl) .AppendPathSegments("items", content.Id, "copy"); var request = new HttpRequestMessage(HttpMethod.Post, url.ToUri()); request.Headers.Authorization = AuthService.Instance.CreateAuthenticationHeader(); var requestContent = new ClipboardItem { Name = content.Name, ParentReference = new ParentReference { DriveId = DriveService.Instance.DriveId, Id = target.Id } }; var json = JsonConvert.SerializeObject(requestContent); request.Content = new StringContent(json, Encoding.UTF8, "application/json"); var response = await Task.Run(() => client.SendAsync(request)); if (response.IsSuccessStatusCode) { var operationUri = response.Headers.Location; // Adding cancellation token for the operation var tokenSource = new CancellationTokenSource(); DriveService.Instance.CurrentOperations.Add(tokenSource); // Waiting for the copying to end var result = await DriveService.AwaitOperationAsync(operationUri, tokenSource.Token); // Removing the cancellation token as the operation already ended DriveService.Instance.CurrentOperations.Remove(tokenSource); //This reloads the target folder into the cache to update its values await DriveService.Instance.LoadItemAsync <DriveFolder>(target.Id); // This results the item to be updated in the cache return(await DriveService.Instance.GetItemAsync(result.ResourceId)); } if (response.StatusCode == HttpStatusCode.Unauthorized && !isRetrying) { await AuthService.Instance.LoginAsync(); return(await ExecuteAsync(content, target, true)); } throw new WebException(await response.Content.ReadAsStringAsync()); } }
/// <summary> /// Adds the root folder to the cache. /// </summary> /// <param name="folder">The root folder of the drive</param> public void AddRootFolder(DriveFolder folder) { if (_itemStorage.ContainsKey(folder.Id)) { _itemStorage[folder.Id].Item = folder; } else { _itemStorage.Add(folder.Id, new CacheItem(folder)); } _rootFolder = folder; }
/// <summary> /// Creates a folder as a child of the target folder and adds it to the list of children /// </summary> /// <param name="parent">The parent of the newly created folder</param> /// <param name="name">The name of the folder to be created</param> /// <param name="isRetrying">Determines if the method is retrying after an unauthorized response</param> /// <returns></returns> public async Task <DriveFolder> CreateFolderAsync(DriveFolder parent, string name, bool isRetrying = false) { using (var client = new HttpClient()) { var url = new Url(BaseUrl) .AppendPathSegments("items", parent.Id, "children"); var request = new HttpRequestMessage(HttpMethod.Post, url.ToUri()); request.Headers.Authorization = AuthService.Instance.CreateAuthenticationHeader(); var content = new JObject { { "name", name }, { "folder", new JObject() }, { "@microsoft.graph.conflictBehaviour", "fail" } }; request.Content = new StringContent(content.ToString(), Encoding.UTF8, "application/json"); var response = await Task.Run(() => client.SendAsync(request)); if (response.IsSuccessStatusCode) { var json = await response.Content.ReadAsStringAsync(); var folder = JsonConvert.DeserializeObject <DriveFolder>(json); Cache.AddItem(folder); return(folder); } if (response.StatusCode == HttpStatusCode.Unauthorized && !isRetrying) { await AuthService.Instance.LoginAsync(); return(await CreateFolderAsync(parent, name, true)); } throw new WebException(await response.Content.ReadAsStringAsync()); } }
/// <summary> /// Moves the given item into the target folder, and also updates cache /// </summary> /// <param name="content">The item to be copied</param> /// <param name="target">The target folder</param> /// <param name="isRetrying">Determines if the method is retrying after an unauthorized response</param> /// <returns>The pasted item</returns> public async Task <DriveItem> ExecuteAsync(DriveItem content, DriveFolder target, bool isRetrying) { using (var client = new HttpClient()) { var url = new Url(DriveService.BaseUrl) .AppendPathSegments("items", content.Id); var request = new HttpRequestMessage(new HttpMethod("PATCH"), url.ToUri()); request.Headers.Authorization = AuthService.Instance.CreateAuthenticationHeader(); var requestContent = new ClipboardItem { Name = content.Name, ParentReference = new ParentReference { Id = target.Id } }; var json = JsonConvert.SerializeObject(requestContent); request.Content = new StringContent(json, Encoding.UTF8, "application/json"); var response = await Task.Run(() => client.SendAsync(request)); if (response.IsSuccessStatusCode) { DriveService.Instance.Cache.MoveItem(content.Id, target.Id); return(content); } if (response.StatusCode != HttpStatusCode.Unauthorized && !isRetrying) { await AuthService.Instance.LoginAsync(); return(await ExecuteAsync(content, target, true)); } throw new WebException(await response.Content.ReadAsStringAsync()); } }
/// <summary> /// Clears all data from the cache. /// </summary> public void Clear() { _itemStorage.Clear(); _rootFolder = null; }