Esempio n. 1
0
        public async Task <DriveItem> UploadLargeFileAsync(Stream stream, string targetPath, int maxSliceSize = -1, IProgress <long> progress = null)
        {
            // TODO: Support fileUploadTask.ResumeAsnyc
            var uploadSession = await AppRoot.ItemWithPath(targetPath)
                                .CreateUploadSession().Request().PostAsync().ConfigureAwait(false);

            var fileUploadTask = new LargeFileUploadTask <DriveItem>(uploadSession, stream, maxSliceSize < 0 ? 1024 * 320 : maxSliceSize);

            try
            {
                var uploadResult = await fileUploadTask.UploadAsync(progress).ConfigureAwait(false);

                if (uploadResult.UploadSucceeded)
                {
                    return(uploadResult.ItemResponse);
                }
                else
                {
                    return(null);
                }
            }
            catch (ServiceException)
            {
                throw;
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Upload a large file using callbacks
        /// </summary>
        /// <param name="graphClient">Client for upload</param>
        /// <param name="itemId">itemId for upload</param>
        /// <returns></returns>
        public static async Task UploadLargeFileWithCallBacks(IBaseClient graphClient, string itemId)
        {
            await using Stream stream = Program.GetFileStream();

            // POST /v1.0/drive/items/01KGPRHTV6Y2GOVW7725BZO354PWSELRRZ:/SWEBOKv3.pdf:/microsoft.graph.createUploadSession
            var uploadSession = await CreateDriveItemUploadSession(graphClient, itemId);

            // Create task
            var maxSliceSize = 320 * 1024; // 320 KB - Change this to your chunk size. 5MB is the default.
            LargeFileUploadTask <DriveItem> largeFileUploadTask = new LargeFileUploadTask <DriveItem>(uploadSession, stream, maxSliceSize);

            // Setup the progress monitoring
            IProgress <long> progress = new Progress <long>(progressCallBack =>
            {
                Console.WriteLine($"Uploaded {progressCallBack} bytes of {stream.Length} bytes");
            });

            try
            {
                var uploadResult = await largeFileUploadTask.UploadAsync(progress);

                if (uploadResult.UploadSucceeded)
                {
                    Console.WriteLine($"File Uploaded {uploadResult.ItemResponse.Id}");//Successful Upload
                }
            }
            catch (ServiceException e)
            {
                Console.WriteLine("Something went wrong with the upload");
                Console.WriteLine(e.Message);
            }
        }
Esempio n. 3
0
        public void ShouldNotThrowArgumentExceptionOnConstructorWithoutSliceSize()
        {
            // Try to upload 1Mb stream without specifying the slice size(should default to 5Mb)
            byte[] mockData = new byte[1000000];
            using (Stream stream = new MemoryStream(mockData))
            {
                // Arrange
                IUploadSession uploadSession = new Graph.Core.Models.UploadSession
                {
                    NextExpectedRanges = new List <string>()
                    {
                        "0-"
                    },
                    UploadUrl          = "http://localhost",
                    ExpirationDateTime = DateTimeOffset.Parse("2019-11-07T06:39:31.499Z")
                };

                // Act with constructor without chunk length
                var fileUploadTask = new LargeFileUploadTask <DriveItem>(uploadSession, stream);
                var uploadSlices   = fileUploadTask.GetUploadSliceRequests();

                // Assert
                //We have only 1 slices
                Assert.Single(uploadSlices);

                var onlyUploadSlice = uploadSlices.First();
                Assert.Equal(stream.Length, onlyUploadSlice.TotalSessionLength);
                Assert.Equal(0, onlyUploadSlice.RangeBegin);
                Assert.Equal(stream.Length - 1, onlyUploadSlice.RangeEnd);
                Assert.Equal(stream.Length, onlyUploadSlice.RangeLength);  //verify the last slice is the right size
            }
        }
Esempio n. 4
0
        public static async Task UploadLargeAttachmentWithCallBack(IBaseClient graphClient, string messageId)
        {
            await using Stream stream = Program.GetFileStream();

            var uploadSession = await CreateFileAttachmentUploadSession(graphClient, messageId, stream.Length);

            // Create task
            var maxSliceSize = 320 * 1024; // 320 KB - Change this to your slice size.
            LargeFileUploadTask <FileAttachment> largeFileUploadTask = new LargeFileUploadTask <FileAttachment>(uploadSession, stream, maxSliceSize);

            // Setup the progress mechanism
            IProgress <long> progress = new Progress <long>(progressCallback =>
            {
                Console.WriteLine($"Uploaded {progressCallback} bytes of {stream.Length} bytes");
            });

            try
            {
                var uploadResult = await largeFileUploadTask.UploadAsync(progress);

                if (uploadResult.UploadSucceeded)
                {
                    Console.WriteLine(uploadResult.Location);
                }
            }
            catch (ServiceException e)
            {
                Console.WriteLine("Something went wrong with the upload");
                Console.WriteLine(e.Message);
            }
        }
Esempio n. 5
0
        public async Task UploadDocumentAsync(string directory, string fileName, Stream content)
        {
            // Based on example at https://docs.microsoft.com/en-us/graph/sdks/large-file-upload?tabs=csharp
            var filePath    = $"{directory}/{fileName}";
            var uploadProps = new DriveItemUploadableProperties
            {
                ODataType      = null,
                AdditionalData = new Dictionary <string, object>
                {
                    { "@microsoft.graph.conflictBehavior", "replace" }
                }
            };

            // Create the upload session
            // itemPath does not need to be a path to an existing item
            var uploadSession = await _client.Drives[_fileStorageConfig.DriveId].Root
                                .ItemWithPath(filePath)
                                .CreateUploadSession(uploadProps)
                                .Request()
                                .PostAsync();

            // Max slice size must be a multiple of 320 KiB
            int maxSliceSize   = 320 * 1024;
            var fileUploadTask = new LargeFileUploadTask <DriveItem>(uploadSession, content, maxSliceSize);

            _logger.LogInformation($"Starting upload file to drive {_fileStorageConfig.DriveId} on path {filePath}");

            // Create a callback that is invoked after each slice is uploaded
            IProgress <long> progress = new Progress <long>(progress => {
                _logger.LogDebug($"Uploaded {progress} bytes of stream");
            });

            try
            {
                var uploadResult = await fileUploadTask.UploadAsync(progress);

                if (uploadResult.UploadSucceeded)
                {
                    _logger.LogInformation($"Uploading file to drive {_fileStorageConfig.DriveId} on path {directory} succeeded (item id: {uploadResult.ItemResponse.Id}");
                }
                else
                {
                    _logger.LogError($"Uploading file to drive {_fileStorageConfig.DriveId} on path {directory} failed.");
                    throw new CodedException("UploadFailed", "Upload failed", $"Uploading file to drive {_fileStorageConfig.DriveId} on path {directory} failed.");
                }
            }
            catch (TaskCanceledException ex)
            {
                _logger.LogError($"Uploading file to drive {_fileStorageConfig.DriveId} on path {directory} failed: {ex.ToString()}");
                throw ex;
            }
            catch (ServiceException ex)
            {
                _logger.LogError($"Uploading file to drive {_fileStorageConfig.DriveId} on path {directory} failed: {ex.ToString()}");
                throw ex;
            }
        }
Esempio n. 6
0
        public async void UploadToOneDrive(string filepath, string onedrivepath)
        {
            var graphServiceClient = new GraphServiceClient(
                new DelegateAuthenticationProvider((requestMessage) =>
            {
                requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", AccessToken);
                return(Task.CompletedTask);
            }));

            //GraphServiceClient graphClient = new GraphServiceClient("https://graph.microsoft.com/v1.0", new DelegateAuthenticationProvider(async (requestMessage) =>
            //{
            //    requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", AccessToken);
            //}));
            using (var fileStream = System.IO.File.OpenRead(filepath))
            {
                // Use properties to specify the conflict behavior
                // in this case, replace
                var uploadProps = new DriveItemUploadableProperties
                {
                    ODataType      = null,
                    AdditionalData = new Dictionary <string, object>
                    {
                        { "@microsoft.graph.conflictBehavior", "replace" }
                    }
                };
                // Create the upload session
                // itemPath does not need to be a path to an existing item
                var uploadSession = await graphServiceClient.Me.Drive.Root.ItemWithPath(onedrivepath).CreateUploadSession(uploadProps).Request().PostAsync();

                // Max slice size must be a multiple of 320 KiB
                int maxSliceSize   = 320 * 1024;
                var fileUploadTask =
                    new LargeFileUploadTask <DriveItem>(uploadSession, fileStream, maxSliceSize);
                try
                {
                    // Upload the file
                    var uploadResult = await fileUploadTask.UploadAsync();

                    if (uploadResult.UploadSucceeded)
                    {
                        toolStripStatusLabel1.Text = filepath + " 上传成功";
                    }
                    else
                    {
                        MessageBox.Show("上传失败,请检查网络!");
                    }
                }
                catch (ServiceException ex)
                {
                    MessageBox.Show($"在上传过程中出现错误: {ex}");
                }
            }
        }
Esempio n. 7
0
        public static async Task <DriveItem> UploadDocumentAsync(IDriveItemRequestBuilder driveItemRequestBuilder, string filename, Stream fileStream, string conflictBehaviour = ConflictBehaviour.Rename)
        {
            UploadSession uploadSession = null;

            try
            {
                var uploadProps = new DriveItemUploadableProperties
                {
                    ODataType      = null,
                    AdditionalData = new Dictionary <string, object>
                    {
                        ["@microsoft.graph.conflictBehavior"] = conflictBehaviour
                    }
                };

                uploadSession = await driveItemRequestBuilder
                                .ItemWithPath(filename)
                                .CreateUploadSession(uploadProps)
                                .Request()
                                .PostAsync();
            }
            catch (ServiceException ex)
            {
                throw new Exception("An error occured while creating upload session.", ex);
            }

            if (uploadSession == null)
            {
                throw new Exception("Upload session is null.");
            }

            try
            {
                // Performs upload, slice by slice
                int maxSliceSize   = 5 * 1024 * 1024; //5MB
                var fileUploadTask = new LargeFileUploadTask <DriveItem>(uploadSession, fileStream, maxSliceSize);
                var uploadResult   = await fileUploadTask.UploadAsync();

                if (!uploadResult.UploadSucceeded)
                {
                    throw new Exception("File upload failed!");
                }
                else
                {
                    return(uploadResult.ItemResponse);
                }
            }
            catch (Exception ex)
            {
                throw new Exception("An error occurred while trying to upload document.", ex);
            }
        }
Esempio n. 8
0
        // Upload attachments
        public async Task <UploadResult <AttachmentItem> > UploadAttachment(UploadSession uploadSession, FileStream attachmentStream)
        {
            int fileSlice = 320 * 1024;

            var fileUploadTask = new LargeFileUploadTask <AttachmentItem>(uploadSession, attachmentStream, fileSlice);

            IProgress <long> progress = new Progress <long>(progress => {
                Console.WriteLine($"Uploaded {progress} bytes of {attachmentStream.Length} bytes");
            });

            // Upload the file
            return(await fileUploadTask.UploadAsync(progress));
        }
        /// <summary>
        /// Take a file greater than 4MB and upload it to the service
        /// </summary>
        /// <param name="fileToUpload">The file that we want to upload</param>
        /// <param name="uploadToSharePoint">Should we upload to SharePoint or OneDrive?</param>
        public async Task <DriveItem> UploadLargeFile(string fileToUpload, bool uploadToSharePoint)
        {
            DriveItem  uploadedFile = null;
            FileStream fileStream   = new FileStream(fileToUpload, FileMode.Open);

            UploadSession uploadSession = null;

            // Do we want OneDrive for Business/Consumer or do we want a SharePoint Site?
            if (uploadToSharePoint)
            {
                uploadSession = await _graphClient.Sites["root"].Drive.Root.ItemWithPath(fileToUpload).CreateUploadSession().Request().PostAsync();
            }
            else
            {
                uploadSession = await _graphClient.Me.Drive.Root.ItemWithPath(fileToUpload).CreateUploadSession().Request().PostAsync();
            }

            if (uploadSession != null)
            {
                // Chunk size must be divisible by 320KiB, our chunk size will be slightly more than 1MB
                int maxSizeChunk   = (320 * 1024) * 4;
                var fileUploadTask = new LargeFileUploadTask <DriveItem>(uploadSession, fileStream, maxSizeChunk);

                // Create a callback that is invoked after each slice is uploaded
                IProgress <long> progress = new Progress <long>(prog =>
                {
                    Console.WriteLine($"Uploaded {prog} bytes of {fileStream.Length} bytes");
                });

                try
                {
                    // Upload the file
                    var uploadResult = await fileUploadTask.UploadAsync(progress);

                    if (uploadResult.UploadSucceeded)
                    {
                        uploadedFile = uploadResult.ItemResponse;
                    }
                    else
                    {
                        Console.WriteLine("Upload failed");
                    }
                }
                catch (ServiceException ex)
                {
                    Console.WriteLine($"Error uploading: {ex.ToString()}");
                }
            }

            return(uploadedFile);
        }
Esempio n. 10
0
        public UploadResult <DriveItem> ReplaceLargeFile(DriveItem item, Stream stream)
        {
            UploadResult <DriveItem> uploadResult = null;

            using (var fileStream = (FileStream)stream)
            {
                var uploadProps = new DriveItemUploadableProperties
                {
                    ODataType      = null,
                    AdditionalData = new Dictionary <string, object>
                    {
                        { "@microsoft.graph.conflictBehavior", "replace" }
                    }
                };

                var uploadSession = graphClient.Drive.Root
                                    .ItemWithPath(item.Name)
                                    .CreateUploadSession(uploadProps)
                                    .Request()
                                    .PostAsync();

                int maxSliceSize   = 320 * 1024;
                var fileUploadTask =
                    new LargeFileUploadTask <DriveItem>(uploadSession.Result, fileStream, maxSliceSize);

                IProgress <long> progress = new Progress <long>(slice =>
                {
                    Console.WriteLine($"Uploaded {slice} bytes of {fileStream.Length} bytes");
                });

                try
                {
                    uploadResult = fileUploadTask.UploadAsync(progress).Result;

                    if (uploadResult.UploadSucceeded)
                    {
                        Console.WriteLine($"Upload complete, item ID: {uploadResult.ItemResponse.Id}");
                    }
                    else
                    {
                        Console.WriteLine("Upload failed");
                    }
                }
                catch (ServiceException ex)
                {
                    Console.WriteLine($"Error uploading: {ex.ToString()}");
                }
            }
            return(uploadResult);
        }
Esempio n. 11
0
        public async Task UploadLargeFileAsync(string siteUrl, string pathToFile)
        {
            var uriSite        = new Uri(siteUrl);
            var siteCollection = await graphServiceClient.Sites.GetByPath(uriSite.AbsolutePath, uriSite.Host).Request().GetAsync();

            var drive = graphServiceClient.Sites[siteCollection.Id].Drive.Root;

            using var fileStream = new FileStream(pathToFile, FileMode.Open, FileAccess.Read);
            var uploadProps = new DriveItemUploadableProperties
            {
                ODataType      = null,
                AdditionalData = new Dictionary <string, object>
                {
                    { "@microsoft.graph.conflictBehavior", "replace" }
                }
            };

            var uploadSession = await drive
                                .ItemWithPath("Engagement Request File/AuvenirApis.docx")
                                .CreateUploadSession(uploadProps)
                                .Request()
                                .PostAsync();

            int maxSliceSize          = 320 * 1024;
            var fileUploadTask        = new LargeFileUploadTask <DriveItem>(uploadSession, fileStream, maxSliceSize);
            IProgress <long> progress = new Progress <long>(progress => {
                Console.WriteLine($"Uploaded {progress} bytes of {fileStream.Length} bytes");
            });

            try
            {
                var uploadResult = await fileUploadTask.UploadAsync(progress);

                if (uploadResult.UploadSucceeded)
                {
                    Console.WriteLine($"Upload complete, item ID: {uploadResult.ItemResponse.Id}");
                }
                else
                {
                    Console.WriteLine("Upload failed");
                }
            }
            catch (ServiceException ex)
            {
                Console.WriteLine($"Error uploading: {ex.ToString()}");
            }
        }
Esempio n. 12
0
        public void BreaksDownStreamIntoRangesCorrectly()
        {
            byte[] mockData = new byte[1000000];//create a stream of about 1M so we can split it into a few 320K slices
            using (Stream stream = new MemoryStream(mockData))
            {
                // Arrange
                IUploadSession uploadSession = new Graph.Core.Models.UploadSession
                {
                    NextExpectedRanges = new List <string>()
                    {
                        "0-"
                    },
                    UploadUrl          = "http://localhost",
                    ExpirationDateTime = DateTimeOffset.Parse("2019-11-07T06:39:31.499Z")
                };

                int maxSliceSize = 320 * 1024;

                // Act
                var fileUploadTask = new LargeFileUploadTask <DriveItem>(uploadSession, stream, maxSliceSize);
                var uploadSlices   = fileUploadTask.GetUploadSliceRequests();

                // Assert
                //We have only 4 slices
                Assert.Equal(4, uploadSlices.Count());

                long currentRangeBegins = 0;
                foreach (var uploadSlice in uploadSlices)
                {
                    Assert.Equal(stream.Length, uploadSlice.TotalSessionLength);
                    Assert.Equal(currentRangeBegins, uploadSlice.RangeBegin);
                    currentRangeBegins += maxSliceSize;
                }

                //The last slice is a a bit smaller than the rest
                var lastUploadSlice = uploadSlices.Last();
                Assert.Equal(stream.Length - 1, lastUploadSlice.RangeEnd);
                Assert.Equal(stream.Length % maxSliceSize, lastUploadSlice.RangeLength); //verify the last slice is the right size
            }
        }
Esempio n. 13
0
        public async Task <bool> UploadFileAsync(StorageFile localFile, CancellationToken cancellationToken)
        {
            if (!await IsAuthenticatedAsync().ConfigureAwait(false))
            {
                return(false);
            }

            try
            {
                bool uploadSucceeded = await CoreHelper.RetryAsync(async() =>
                {
                    using (await _semaphore.WaitAsync(cancellationToken).ConfigureAwait(false))
                        using (IRandomAccessStream localFileContent = await localFile.OpenReadAsync())
                            using (Stream localFileContentStream = localFileContent.AsStreamForRead())
                            {
                                // the main data file may be > 4 MB, so we use an upload session in case.
                                UploadSession uploadSession = await _graphClient.Drive.Special.AppRoot
                                                              .ItemWithPath(localFile.Name)
                                                              .CreateUploadSession().Request()
                                                              .PostAsync(cancellationToken).ConfigureAwait(false);

                                var largeFileUploadTask = new LargeFileUploadTask <DriveItem>(uploadSession, localFileContentStream, TransferBufferSize);

                                UploadResult <DriveItem> uploadedFile = await largeFileUploadTask.UploadAsync().ConfigureAwait(false);

                                return(uploadedFile.UploadSucceeded);
                            }
                }).ConfigureAwait(false);

                _logger.LogEvent(UploadFileEvent, $"Upload succeeded == {uploadSucceeded}");

                return(uploadSucceeded);
            }
            catch (Exception ex)
            {
                _logger.LogFault(UploadFileFaultEvent, "Unable to upload a file.", ex);
                return(false);
            }
        }
Esempio n. 14
0
        private async Task <bool> MessageCreateUploadSession(string messageId, string fileName, byte[] bytes)
        {
            try
            {
                using (Stream stream = new MemoryStream(bytes))
                {
                    var attachmentItem = new AttachmentItem
                    {
                        AttachmentType = AttachmentType.File,
                        Name           = fileName,
                        Size           = stream.Length
                    };

                    var uploadSession = await graphClient.Me.Messages[messageId].Attachments
                                        .CreateUploadSession(attachmentItem)
                                        .Request()
                                        .PostAsync();

                    var maxChunkSize        = 320 * 1024;
                    var largeFileUploadTask = new LargeFileUploadTask <FileAttachment>(uploadSession, stream, maxChunkSize);

                    var uploadResult = await largeFileUploadTask.UploadAsync();

                    if (uploadResult.UploadSucceeded)
                    {
                        return(true);
                    }

                    return(false);
                }
            }
            catch (Exception ex)
            {
                //Logger.ErrorFormat("CreateUploadSession - Upload failed ex: {0}", ex);
                return(false);
            }
        }
        /// <summary>
        /// Allows you to send files to sharepoint. Repository: https://github.com/MarcinMichnik-HiQ/Frends.Office
        /// </summary>
        /// <param name="input"></param>
        /// <returns>Returns JToken.</returns>
        public static async Task <JToken> ExportFileToSharepoint(ExportFileToSharepointInput input)
        {
            IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
                                                                           .Create(input.clientID)
                                                                           .WithTenantId(input.tenantID)
                                                                           .WithClientSecret(input.clientSecret)
                                                                           .Build();

            ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication);

            // Create a new instance of GraphServiceClient with the authentication provider.
            IGraphServiceClient graphClient = new GraphServiceClient(authProvider);
            string fileLength;
            string url = "";

            // Get fileName from the sourceFilePath
            string[] sourcePathSplit = input.sourceFilePath.Split('\\');
            string   fileName        = sourcePathSplit.Last();

            try
            {
                using (FileStream fileStream = System.IO.File.OpenRead(input.sourceFilePath))
                {
                    fileLength = fileStream.Length.ToString();
                    try
                    {
                        // Use properties to specify the conflict behavior
                        // in this case, replace
                        DriveItemUploadableProperties uploadProps = new DriveItemUploadableProperties
                        {
                            ODataType      = null,
                            AdditionalData = new Dictionary <string, object>
                            {
                                { "@microsoft.graph.conflictBehavior", "replace" }
                            }
                        };

                        // Create the upload session
                        // itemPath does not need to be a path to an existing item
                        UploadSession uploadSession = await graphClient
                                                      .Sites[input.siteID]
                                                      .Drives[input.driveID]
                                                      .Root
                                                      .ItemWithPath(input.targetFolderPath + fileName)
                                                      .CreateUploadSession(uploadProps)
                                                      .Request()
                                                      .PostAsync();

                        // Max slice size must be a multiple of 320 KiB
                        int maxSliceSize = 320 * 2048;
                        LargeFileUploadTask <DriveItem> fileUploadTask =
                            new LargeFileUploadTask <DriveItem>(uploadSession, fileStream, maxSliceSize);

                        // Create a callback that is invoked after each slice is uploaded
                        IProgress <long> progress = new Progress <long>();

                        url = uploadSession.UploadUrl;

                        try
                        {
                            // Upload the file
                            UploadResult <DriveItem> uploadResult = await fileUploadTask.UploadAsync(progress);
                        }
                        catch (ServiceException ex)
                        {
                            await fileUploadTask.DeleteSessionAsync();

                            throw new Exception("Unable to send file.", ex);
                        }
                    }
                    catch (ServiceException ex) {
                        throw new Exception("Unable to establish connection to Sharepoint.", ex);
                    }
                }
            }
            catch (ServiceException ex) {
                throw new Exception("Unable to open file.", ex);
            }

            JToken taskResponse = JToken.Parse("{}");

            taskResponse["FileSize"]         = fileLength;
            taskResponse["Path"]             = input.sourceFilePath.ToString();
            taskResponse["FileName"]         = fileName.ToString();
            taskResponse["TargetFolderName"] = input.targetFolderPath.ToString();
            taskResponse["ClientID"]         = input.clientID;
            taskResponse["TenantID"]         = input.tenantID.ToString();
            taskResponse["SiteID"]           = input.siteID.ToString();
            taskResponse["DriveID"]          = input.driveID.ToString();
            taskResponse["UploadUrl"]        = url;

            return(taskResponse);
        }
        public static void Main(string[] args)
        {
            var config = LoadAppSettings();

            if (config == null)
            {
                Console.WriteLine("Invalid appsettings.json file.");
                return;
            }

            var client = GetAuthenticatedGraphClient(config);

            var profileResponse = client.Me.Request().GetAsync().Result;

            Console.WriteLine("Hello " + profileResponse.DisplayName);

            // request 1 - upload small file to user's onedrive
            // var fileName = "smallfile.txt";
            // var filePath = Path.Combine(System.IO.Directory.GetCurrentDirectory(), fileName);
            // Console.WriteLine("Uploading file: " + fileName);

            // FileStream fileStream = new FileStream(filePath, FileMode.Open);
            // var uploadedFile = client.Me.Drive.Root
            //                               .ItemWithPath("smallfile.txt")
            //                               .Content
            //                               .Request()
            //                               .PutAsync<DriveItem>(fileStream)
            //                               .Result;
            // Console.WriteLine("File uploaded to: " + uploadedFile.WebUrl);

            // request 2 - upload large file to user's onedrive
            var fileName = "largefile.zip";
            var filePath = Path.Combine(System.IO.Directory.GetCurrentDirectory(), fileName);

            Console.WriteLine("Uploading file: " + fileName);

            // load resource as a stream
            using (Stream stream = new FileStream(filePath, FileMode.Open))
            {
                var uploadSession = client.Me.Drive.Root
                                    .ItemWithPath(fileName)
                                    .CreateUploadSession()
                                    .Request()
                                    .PostAsync()
                                    .Result;

                // create upload task
                var maxChunkSize    = 320 * 1024;
                var largeUploadTask = new LargeFileUploadTask <DriveItem>(uploadSession, stream, maxChunkSize);

                // create progress implementation
                IProgress <long> uploadProgress = new Progress <long>(uploadBytes =>
                {
                    Console.WriteLine($"Uploaded {uploadBytes} bytes of {stream.Length} bytes");
                });

                // upload file
                UploadResult <DriveItem> uploadResult = largeUploadTask.UploadAsync(uploadProgress).Result;
                if (uploadResult.UploadSucceeded)
                {
                    Console.WriteLine("File uploaded to user's OneDrive root folder.");
                }
            }
        }
Esempio n. 17
0
        public async Task <(CloudStorageResult, CloudStorageFile)> UploadFileToFolderByIdAsync(string filePath, string folderId, CancellationToken ct)
        {
            IDriveItemRequestBuilder driveItemsRequest;

            if (string.IsNullOrEmpty(folderId))
            {
                driveItemsRequest = myDriveBuilder.Root;
            }
            else
            {
                driveItemsRequest = myDriveBuilder.Items[folderId];
            }

            CloudStorageResult result = new CloudStorageResult();
            CloudStorageFile   file   = null;

            // Use properties to specify the conflict behavior in this case, replace
            var uploadProps = new DriveItemUploadableProperties
            {
                ODataType      = null,
                AdditionalData = new Dictionary <string, object>
                {
                    { "@microsoft.graph.conflictBehavior", "replace" }
                }
            };


            try
            {
                // Create an upload session for a file with the same name of the user selected file
                UploadSession session = await driveItemsRequest.ItemWithPath(Path.GetFileName(filePath)).CreateUploadSession(uploadProps).Request().PostAsync(ct);

                using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
                {
                    var fileUploadTask = new LargeFileUploadTask <DriveItem>(session, fileStream, CHUNK_SIZE);

                    // Create a callback that is invoked after each slice is uploaded
                    IProgress <long> progressCallback = new Progress <long>((progress) =>
                    {
                        Console.WriteLine($"Uploaded {progress} bytes.");
                        OnProgressChanged(progress);
                    });

                    // Upload the file
                    var uploadResult = await fileUploadTask.UploadAsync(progressCallback);

                    if (uploadResult.UploadSucceeded)
                    {
                        // The ItemResponse object in the result represents the created item.
                        file = new CloudStorageFile()
                        {
                            Name         = uploadResult.ItemResponse.Name,
                            Id           = uploadResult.ItemResponse.Id,
                            CreatedTime  = uploadResult.ItemResponse.CreatedDateTime?.DateTime ?? DateTime.MinValue,
                            ModifiedTime = uploadResult.ItemResponse.LastModifiedDateTime?.DateTime ?? DateTime.MinValue,
                            Size         = uploadResult.ItemResponse.Size ?? 0
                        };
                        result.Status = Status.Success;
                    }
                    else
                    {
                        result.Message = "Upload failed.";
                    }
                }
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
            }

            return(result, file);
        }
Esempio n. 18
0
        private void UploadFile(string path, MemoryStream stream)
        {
            try
            {
                Task.Run(async() =>
                {
                    PathItemBuilder pathItemBuilder = await GetPathItemBuilder(path);
                    //for small files <2MB use the direct upload:
                    if (stream.Length < 2 * 1024 * 1024)
                    {
                        return(await
                               pathItemBuilder
                               .getPathItem()
                               .Content
                               .Request()
                               .PutAsync <DriveItem>(stream));
                    }

                    //for larger files use an upload session. This is required for 4MB and beyond, but as the docs are not very clear about this
                    //limit, let's use it a bit more often to be safe.

                    var uploadProps = new DriveItemUploadableProperties
                    {
                        ODataType      = null,
                        AdditionalData = new Dictionary <string, object>
                        {
                            { "@microsoft.graph.conflictBehavior", "replace" }
                        }
                    };


                    var uploadSession = await pathItemBuilder
                                        .getPathItem()
                                        .CreateUploadSession(uploadProps)
                                        .Request()
                                        .PostAsync();

                    // Max slice size must be a multiple of 320 KiB
                    int maxSliceSize   = 320 * 1024;
                    var fileUploadTask = new LargeFileUploadTask <DriveItem>(uploadSession, stream, maxSliceSize);
                    var uploadResult   = await fileUploadTask.UploadAsync();

                    if (!uploadResult.UploadSucceeded)
                    {
                        throw new Exception("Failed to upload data!");
                    }

                    return(uploadResult.ItemResponse);
                }).Wait();
            }
            catch (Exception e)
            {
                Task.Run(async() =>
                {
                    PathItemBuilder pathItemBuilder = await GetPathItemBuilder(path);
                    pathItemBuilder.verbose         = true;
                    pathItemBuilder.getPathItem();
                }).Wait();
                throw convertException(e);
            }
        }
Esempio n. 19
0
        // Upload File to Onedrive
        public async Task <string> transferDataToOnedrive(String FilePath)
        {
            var fileName = Path.GetFileName(FilePath);

            if (null == this.graphClient)
            {
                return("");
            }

            Label lb = (Label)System.Windows.Forms.Application.OpenForms["Form1"].Controls.Find("label4", false).FirstOrDefault();

            using (var fileStream = System.IO.File.OpenRead(FilePath))
            {
                // Use properties to specify the conflict behavior
                // in this case, replace
                var uploadProps = new DriveItemUploadableProperties
                {
                    ODataType      = null,
                    AdditionalData = new Dictionary <string, object>
                    {
                        { "@microsoft.graph.conflictBehavior", "replace" }
                    }
                };

                // Create the upload session
                // itemPath does not need to be a path to an existing item
                var uploadSession = await graphClient.Me.Drive.Root
                                    .ItemWithPath("ClipboardShare/" + fileName)
                                    .CreateUploadSession(uploadProps)
                                    .Request()
                                    .PostAsync();



                int maxSliceSize   = UploadDownloadChunkSize;
                var fileUploadTask =
                    new LargeFileUploadTask <DriveItem>(uploadSession, fileStream, maxSliceSize);

                // Create a callback that is invoked after each slice is uploaded
                IProgress <long> progress = new Progress <long>(progress =>
                {
                    Console.WriteLine($"Uploaded {progress} bytes of {fileStream.Length} bytes");
                    lb.Text = StaticHelpers.BytesToString(progress) + " " + ($" from { StaticHelpers.BytesToString(fileStream.Length) }");
                });

                try
                {
                    // Upload the file
                    var uploadResult = await fileUploadTask.UploadAsync(progress);

                    if (uploadResult.UploadSucceeded)
                    {
                        // The ItemResponse object in the result represents the
                        // created item.
                        Console.WriteLine($"Upload complete, item ID: {uploadResult.ItemResponse.Id}");
                    }
                    else
                    {
                        Console.WriteLine("Upload failed");
                    }
                }
                catch (ServiceException ex)
                {
                    Console.WriteLine($"Error uploading: {ex.ToString()}");
                }
            }
            lb.Text = "";
            return("");
        }
Esempio n. 20
0
        public async Task <IActionResult> UploadFile(string folderId,
                                                     List <IFormFile> uploadFiles)
        {
            if (string.IsNullOrEmpty(folderId))
            {
                return(RedirectToAction("UploadFile")
                       .WithError("No folder ID was specified"));
            }

            try
            {
                var graphClient = GetGraphClientForScopes(_filesScopes);

                var file = uploadFiles.First();

                // Use properties to specify the conflict behavior
                // in this case, replace
                var uploadProps = new DriveItemUploadableProperties
                {
                    ODataType      = null,
                    AdditionalData = new Dictionary <string, object>
                    {
                        { "@microsoft.graph.conflictBehavior", "replace" }
                    }
                };

                // POST /me/drive/items/folderId:/fileName:/createUploadSession
                var uploadSession = await graphClient.Me
                                    .Drive
                                    .Items[folderId]
                                    .ItemWithPath(file.FileName)
                                    .CreateUploadSession(uploadProps)
                                    .Request()
                                    .PostAsync();

                // Max slice size must be a multiple of 320 KiB
                // This amount of bytes will be uploaded each iteration
                int maxSliceSize   = 320 * 1024;
                var fileUploadTask =
                    new LargeFileUploadTask <DriveItem>(uploadSession, file.OpenReadStream(), maxSliceSize);

                // Create a callback that is invoked after each slice is uploaded
                IProgress <long> callback = new Progress <long>(progress => {
                    _logger.LogInformation($"Uploaded {progress} bytes of {file.Length} bytes");
                });

                // Start the upload
                var uploadResult = await fileUploadTask.UploadAsync(callback);

                if (uploadResult.UploadSucceeded)
                {
                    // On success, the new file is contained in the
                    // ItemResponse property of the result
                    return(RedirectToAction("Display", new { fileId = uploadResult.ItemResponse.Id })
                           .WithSuccess("File uploaded"));
                }

                return(RedirectToAction("Index", new { folderId = folderId })
                       .WithError("Error uploading file"));
            }
            catch (ServiceException ex)
            {
                InvokeAuthIfNeeded(ex);

                return(RedirectToAction("Index", new { folderId = folderId })
                       .WithError("Error uploading file", ex.Error.Message));
            }
        }