public Task<LiveOperationResult> UploadAsync(string path, IFileSource fileSource, OverwriteOption option, IBackgroundTransferProvider btu, CancellationToken ct, IProgress<LiveOperationProgress> progress) { if (string.IsNullOrEmpty(path)) { throw new ArgumentException( "path", String.Format(CultureInfo.CurrentUICulture, ResourceHelper.GetString("UrlInvalid"), "path")); } if (null == fileSource) { throw new ArgumentNullException( "fileSource", String.Format(CultureInfo.CurrentUICulture, ResourceHelper.GetString("InvalidNullParameter"), "fileSource")); } if (null != fileSource && string.IsNullOrEmpty(fileSource.Filename)) { throw new ArgumentException( "fileName", String.Format(CultureInfo.CurrentUICulture, ResourceHelper.GetString("InvalidNullOrEmptyParameter"), "fileName")); } if (null == btu) { btu = new Microsoft.Live.Transfers.BasicTransferProvider(); } ApiOperation op = btu.GetUploadOperation(this, this.GetResourceUri(path, ApiMethod.Upload), fileSource, option, progress, syncContext); return this.ExecuteApiOperation(op, ct); }
/// <summary> /// Upload a file to the server. /// </summary> /// <param name="path">relative or absolute uri to the location where the file should be uploaded to.</param> /// <param name="fileName">name for the uploaded file.</param> /// <param name="inputStream">Stream that contains the file content.</param> /// <param name="option"> /// a enum to specify the overwrite behavior if a file with the same name already exists. /// Default is DoNotOverwrite. /// </param> public Task<LiveOperationResult> UploadAsync( string path, string fileName, Stream inputStream, OverwriteOption option) { return this.UploadAsync(path, fileName, inputStream, option, new CancellationToken(false), null); }
public ForegroundUploadOperation(LiveConnectClient client, Uri url, string filename, IFileSource inputFile, OverwriteOption option, IProgress<LiveOperationProgress> progress, SynchronizationContextWrapper syncContext) : base(client, url, ApiMethod.Upload, null, syncContext) { this.Filename = filename; this.Progress = progress; this.OverwriteOption = option; this.FileSource = inputFile; }
public GetUploadLinkOperation( LiveConnectClient client, Uri url, string fileName, OverwriteOption option, SynchronizationContextWrapper syncContext) : base(client, url, ApiMethod.Get, null, syncContext) { this.FileName = fileName; this.OverwriteOption = option; }
/// <summary> /// This class implements the upload operation on Windows 8 using the background uploader. /// </summary> /// <remarks>This constructor is used when uploading a stream created by the application.</remarks> internal TailoredUploadOperation( LiveConnectClient client, Uri url, string fileName, OverwriteOption option, IProgress<LiveOperationProgress> progress, SynchronizationContextWrapper syncContext) : base(client, url, ApiMethod.Upload, null, syncContext) { this.FileName = fileName; this.Progress = progress; this.OverwriteOption = option; }
/// <summary> /// This class implements the upload operation on Windows 8 using the background uploader. /// </summary> /// <remarks>This constructor is used when uploading a stream created by the application.</remarks> public TailoredUploadOperation( LiveConnectClient client, Uri url, string fileName, IInputStream inputStream, OverwriteOption option, IProgress<LiveOperationProgress> progress, SynchronizationContextWrapper syncContext) : this(client, url, fileName, option, progress, syncContext) { Debug.Assert(inputStream != null, "inputStream is null."); this.InputStream = inputStream; }
/// <summary> /// This class implements the upload operation on Windows 8 using the background uploader. /// </summary> /// <remarks>This constructor is used when uploading a stream created by the application.</remarks> public CreateBackgroundUploadOperation( LiveConnectClient client, Uri url, string fileName, IInputStream inputStream, OverwriteOption option) : base(client, url, ApiMethod.Upload, null, null) { Debug.Assert(inputStream != null, "inputStream is null."); this.InputStream = inputStream; this.FileName = fileName; this.OverwriteOption = option; }
public UploadOperation( LiveConnectClient client, Uri url, string fileName, Stream inputStream, OverwriteOption option, object progress, SynchronizationContextWrapper syncContext) : base(client, url, ApiMethod.Upload, null, syncContext) { this.FileName = fileName; this.OverwriteOption = option; this.InputStream = inputStream; this.progress = progress; this.totalBytesToSend = this.InputStream.CanSeek ? this.InputStream.Length : UploadOperation.UnknownFileSize; }
public static void Download( [Required] [Description("Artifactory Url")] string url, [Required] [Description("Artifactory user")] string user, [Required] [Description("Artifactory password")] string password, [Required] [Description("Project Mvn coordinates, e.g. 'com.forcam.lib.project.forcam,ff-rd-08,1.0' or 'com.forcam.lib.project.forcam,ff-rd-08,latest'")] string project, [DefaultValue(false)] [Description("Clean workspace")] bool clean, [DefaultValue(OverwriteOption.Abort)] [Description("Overwrite option")] OverwriteOption @overwrite) { var import = Factory.ImportExport; if (!import.IsNewWorkspace(WorkingDir)) { Console.Error.WriteLine(WorkingDir + " does not appear to be a possible workspace. Needs to be in a git repo."); Environment.Exit(1); } var mvnCoordinates = Project.Parse(project); var download = Factory.CreateUploadDownload(url, user, password); using (var temp = Factory.GetTemporaryDirectory(WorkingDir)) { download.Download(mvnCoordinates, temp.Path); if (clean) { import.CleanWorkspace(WorkingDir); } import.ImportDirecory(temp.Path); import.CopyWorkplace(temp.Path, WorkingDir, overwrite); } }
public void TestExecuteMethod() { WebRequestFactory.Current = new TestWebRequestFactory(); LiveConnectClient connectClient = new LiveConnectClient(new LiveConnectSession()); Uri requestUri = new Uri("http://foo.com"); string fileName = "fileName.txt"; IStorageFile inputFile = new StorageFileStub(); OverwriteOption option = OverwriteOption.Overwrite; IProgress <LiveOperationProgress> progress = new Progress <LiveOperationProgress>(); SynchronizationContextWrapper syncContext = SynchronizationContextWrapper.Current; var tailoredUploadOperation = new TailoredUploadOperation( connectClient, requestUri, fileName, inputFile, option, progress, syncContext); }
/// <summary> /// Uploads a file into the OneDriveItem this command is called on. This command is only available on OneDriveItem instances that represents /// a folder or album. /// </summary> /// <param name="sourceItem"></param> /// <param name="option"></param> /// <param name="btp"></param> /// <param name="progress"></param> /// <returns></returns> public async Task <OneDriveItem> UploadFileAsync(IFileSource sourceItem, OverwriteOption option, IBackgroundTransferProvider btp = null, IProgress <LiveOperationProgress> progress = null) { if (this.ItemType != OneDriveItemType.Folder && this.ItemType != OneDriveItemType.Album) { throw new InvalidOperationException("Cannot upload files to items that do not represent a folder or album"); } LiveOperationResult result = await Client.LiveClient.UploadAsync( string.Format("/{0}", this.Identifier), sourceItem, option, btp, progress); System.Diagnostics.Debug.WriteLine("UploadFile Result: {0}", result.RawResult); FileUploadResult fur = FileUploadResult.FromJson(result.RawResult); return(await this.Client.GetItemFromIdentifier(fur.Identifier)); }
/// <summary> /// Creates a background upload operation. /// </summary> /// <param name="path">relative or absolute uri to the location where the file should be uploaded to.</param> /// <param name="fileName">name for the uploaded file.</param> /// <param name="inputStream">Stream that contains the upload's content.</param> /// <param name="option">an enum to specify the overwrite behavior if a file with the same name already exists.</param> /// <returns>A Task object representing the asynchronous operation.</returns> public Task <LiveUploadOperation> CreateBackgroundUploadAsync( string path, string fileName, IInputStream inputStream, OverwriteOption option) { if (string.IsNullOrEmpty(path)) { throw new ArgumentException( "path", String.Format(CultureInfo.CurrentUICulture, ResourceHelper.GetString("UrlInvalid"), "path")); } if (string.IsNullOrEmpty(fileName)) { throw new ArgumentException( "fileName", String.Format(CultureInfo.CurrentUICulture, ResourceHelper.GetString("InvalidNullOrEmptyParameter"), "fileName")); } if (inputStream == null) { throw new ArgumentNullException( "inputStream", String.Format(CultureInfo.CurrentUICulture, ResourceHelper.GetString("InvalidNullParameter"), "inputStream")); } var op = new CreateBackgroundUploadOperation( this, this.GetResourceUri(path, ApiMethod.Upload), fileName, inputStream, option); return(op.ExecuteAsync()); }
/// <summary> /// Create object with content and progress when upload /// </summary> /// <param name="locationid">Location id where you want to object create</param> /// <param name="name">Object name</param> /// <param name="file">Object content</param> /// <param name="owoption">Overwrite option</param> /// <param name="handler">Progress handler for watch progress when uploading</param> /// <returns>Returns created object</returns> public static T Create(T fileValue, Stream file, OverwriteOption overwriteOption, RequestProgressHandler handler) { T obj = default(T); AFiles <T> fileobj = (fileValue as AFiles <T>); if (string.IsNullOrEmpty((fileobj as AFiles <T>).ParentId)) { fileobj.ParentId = "me/skydrive"; } try { QueryParameters qp = new QueryParameters(); qp.Add("overwrite", GetOverwriteOption(overwriteOption)); RequestObject ro = new RequestObject { Url = UrlBuilder1.Build(fileobj.ParentId + "/files/" + fileobj.Name, qp), Method = WebRequestMethods.Http.Put, ContentType = ContentType.ApplicationJsonODataVerbose }; ro.SetData(new byte[] { 0 }); obj = Requester.Request <T>(ro).ElementAt(0); fileValue = Get((obj as AOperational <T>).Id); } catch { throw; } string[] lid = fileobj.ParentId.Split('.'); string usrid = User.Get("").Id; try { UploadContent(file, usrid, fileobj.Name, lid[lid.Length - 1], 0, handler, null, obj); } catch { throw; } return(obj); }
/// <summary> /// Upload a file to the server. /// </summary> /// <param name="path">relative or absolute uri to the location where the file should be uploaded to.</param> /// <param name="fileName">name for the uploaded file.</param> /// <param name="inputFile">the file object of the local file to be uploaded.</param> /// <param name="option">an enum to specify the overwrite behavior if a file with the same name already exists.</param> /// <param name="ct">a token that is used to cancel the upload operation.</param> /// <param name="progress">an object that is called to report the upload's progress.</param> /// <returns>A Task object representing the asynchronous operation.</returns> public Task <LiveOperationResult> BackgroundUploadAsync( string path, string fileName, IStorageFile inputFile, OverwriteOption option, CancellationToken ct, IProgress <LiveOperationProgress> progress) { if (string.IsNullOrEmpty(path)) { throw new ArgumentException("path", String.Format(CultureInfo.CurrentUICulture, ResourceHelper.GetString("UrlInvalid"), "path")); } if (string.IsNullOrEmpty(fileName)) { throw new ArgumentException("fileName", String.Format(CultureInfo.CurrentUICulture, ResourceHelper.GetString("InvalidNullOrEmptyParameter"), "fileName")); } if (inputFile == null) { throw new ArgumentNullException("inputFile", String.Format(CultureInfo.CurrentUICulture, ResourceHelper.GetString("InvalidNullParameter"), "inputFile")); } ApiOperation op = new TailoredUploadOperation( this, this.GetResourceUri(path, ApiMethod.Upload), fileName, inputFile, option, progress, null); return(this.ExecuteApiOperation(op, ct)); }
public void Upload(DirectoryInfo path, OverwriteOption overwrite, bool dryRun) { var project = ImportExport.ReadProjectStructure(path); var uploads = new List <MavenCoordinates>(); if (overwrite != OverwriteOption.Replace) { foreach (var dep in project.Dependencies) { uploads.AddRange(Verify(dep, overwrite)); } uploads.AddRange(Verify(project, overwrite)); } else { uploads.AddRange(project.Dependencies); uploads.Add(project); } if (dryRun) { foreach (var dep in uploads) { Logger.Info("Skipped upload of " + dep + " as this is a dry run"); } return; } foreach (var dep in uploads) { Upload(project, path, dep); } }
public async Task<FileInfo> UploadAsync(string parentFolderId, Stream content, string name, OverwriteOption overwrite = OverwriteOption.DoNotOverwrite, bool downsizePhotoUpload = false, bool checkForQuota = false) { if (checkForQuota) { var quota = await QuotaAsync().ConfigureAwait(false); if (quota.Available <= content.Length) throw new NotEnoughQuotaException(); } return await Execute<FileInfo>(() => RequestGenerator.Upload(parentFolderId, name, content, overwrite, downsizePhotoUpload)).ConfigureAwait(false); }
public ApiOperation GetUploadOperation(LiveConnectClient client, Uri url, IFileSource inputFile, OverwriteOption option, IProgress <LiveOperationProgress> progress, SynchronizationContextWrapper syncContext) { return(new UploadOperation(client, url, inputFile.Filename, inputFile.GetReadStream(), option, progress, syncContext)); }
public static string GetOverwriteValue(OverwriteOption option) { return uploadOptionToOverwriteValue[option]; }
/// <summary> /// Upload a file to the server. /// </summary> /// <param name="path">relative or absolute uri to the location where the file should be uploaded to.</param> /// <param name="fileName">name for the uploaded file.</param> /// <param name="inputFile">the file object of the local file to be uploaded.</param> /// <param name="option">an enum to specify the overwrite behavior if a file with the same name already exists.</param> /// <returns>A Task object representing the asynchronous operation.</returns> public Task<LiveOperationResult> BackgroundUploadAsync( string path, string fileName, IStorageFile inputFile, OverwriteOption option) { return this.BackgroundUploadAsync(path, fileName, inputFile, option, new CancellationToken(false), null); }
private IEnumerator <IAsyncResult> PutBlobImpl(string contentType, long contentLength, byte[] serviceMetadata, byte[] applicationMetadata, byte[][] blockList, BlockSource[] blockSourceList, byte[] contentMD5, OverwriteOption overwriteOption, IBlobObjectCondition condition, AsyncIteratorContext <NoResults> context) { IStringDataEventStream verboseDebug = Logger <INormalAndDebugLogger> .Instance.VerboseDebug; object[] objArray = new object[] { contentType, this.ContentLength, serviceMetadata, applicationMetadata, blockList, overwriteOption, condition, base.Timeout }; verboseDebug.Log("PutBlobImpl.PutBlobImpl({0};{1};{2};{3};{4};{5};{6};{7})", objArray); IAsyncResult asyncResult = this._storageManager.AsyncProcessor.BeginExecute((TimeSpan param0) => { using (TransactionScope transactionScope = new TransactionScope()) { using (DevelopmentStorageDbDataContext dbContext = DevelopmentStorageDbDataContext.GetDbContext()) { base.LoadContainer(dbContext); string str = null; BlockBlob blockBlob = base.TryLoadBlockBlob(dbContext, out str); DateTime utcNow = DateTime.UtcNow; bool flag = false; if (blockBlob != null) { DbBlobObject.CheckCopyState(blockBlob); flag = DbBlobObject.CheckConditionsAndReturnResetRequired(blockBlob, new BlobLeaseInfo(blockBlob, utcNow), condition, null, true); if (blockBlob.IsCommitted.Value) { if (overwriteOption == OverwriteOption.CreateNewOnly) { throw new BlobAlreadyExistsException(); } } else if (overwriteOption == OverwriteOption.UpdateExistingOnly && condition != null && !condition.IsIncludingUncommittedBlobs) { throw new ConditionNotMetException(); } } else { if (overwriteOption == OverwriteOption.UpdateExistingOnly) { if (condition == null || !condition.LeaseId.HasValue) { throw new ConditionNotMetException(); } throw new LeaseNotPresentException(); } StorageStampHelpers.CheckBlobName(this._blob.BlobName, this._blob.ContainerName); if (string.IsNullOrEmpty(str)) { str = BlockBlobDataManager.CreateUniqueDirectoryLoadBalanced(); } blockBlob = new BlockBlob() { AccountName = this._blob.AccountName, ContainerName = this._blob.ContainerName, BlobName = this._blob.BlobName, VersionTimestamp = DateTime.SpecifyKind(DateTime.MaxValue, DateTimeKind.Utc), IsCommitted = new bool?(false), DirectoryPath = str }; dbContext.Blobs.InsertOnSubmit(blockBlob); } StorageStampHelpers.ValidatePutBlockListArguments(this, contentLength, applicationMetadata, blockList, blockSourceList, contentMD5, condition, this._blobServiceVersion); blockBlob.ContentType = contentType ?? "application/octet-stream"; blockBlob.ContentMD5 = contentMD5; blockBlob.ServiceMetadata = serviceMetadata; blockBlob.Metadata = applicationMetadata; blockBlob.HasBlock = new bool?(true); blockBlob.GenerationId = Guid.NewGuid().ToString(); blockBlob.SnapshotCount = 0; base.ResetBlobLeaseToAvailable(blockBlob, flag); dbContext.SubmitChanges(); DateTime?nullable = null; StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < (int)blockList.Length; i++) { DbListBlobObject.SerializeCommitBlockListEntry(stringBuilder, blockList[i], (blockSourceList != null ? blockSourceList[i] : BlockSource.Uncommitted)); } dbContext.CommitBlockList(this._blob.AccountName, this._blob.ContainerName, this._blob.BlobName, stringBuilder.ToString(), ref nullable); transactionScope.Complete(); blockBlob.LastModificationTime = nullable; this._blob = blockBlob; this.LeaseInfo = new BlobLeaseInfo(blockBlob, utcNow); } } }, base.Timeout, context.GetResumeCallback(), context.GetResumeState("DbListBlobObject.PutBlob")); yield return(asyncResult); this._storageManager.AsyncProcessor.EndExecute(asyncResult); }
private IEnumerator <IAsyncResult> PutBlobImpl(string contentType, long contentLength, byte[] serviceMetadata, byte[] applicationMetadata, Stream inputStream, byte[] contentMD5, bool invokeGeneratePutBlobServiceMetadata, GeneratePutBlobServiceMetadata generatePutBlobServiceMetadata, bool isLargeBlockBlobRequest, ISequenceNumberUpdate sequenceNumberUpdate, OverwriteOption overwriteOption, IBlobObjectCondition condition, AsyncIteratorContext <NoResults> context) { IAsyncResult asyncResult = this._storageManager.AsyncProcessor.BeginExecute((TimeSpan param0) => { long num; long num1; using (TransactionScope transactionScope = new TransactionScope()) { using (DevelopmentStorageDbDataContext dbContext = DevelopmentStorageDbDataContext.GetDbContext()) { base.LoadContainer(dbContext); string str = null; BlockBlob blockBlob = base.TryLoadBlockBlob(dbContext, out str); DateTime utcNow = DateTime.UtcNow; bool flag = false; if (blockBlob != null) { if (blockBlob.IsCommitted.Value && overwriteOption == OverwriteOption.CreateNewOnly) { throw new BlobAlreadyExistsException(); } DbBlobObject.CheckCopyState(blockBlob); flag = DbBlobObject.CheckConditionsAndReturnResetRequired(blockBlob, new BlobLeaseInfo(blockBlob, utcNow), condition, null, true); dbContext.ClearUncommittedBlocks(this._blob.AccountName, this._blob.ContainerName, this._blob.BlobName); dbContext.Refresh(RefreshMode.KeepChanges, blockBlob); } else { if (overwriteOption == OverwriteOption.UpdateExistingOnly) { if (condition == null || !condition.LeaseId.HasValue) { throw new ConditionNotMetException(); } throw new LeaseNotPresentException(); } StorageStampHelpers.CheckBlobName(this._blob.BlobName, this._blob.ContainerName); if (string.IsNullOrEmpty(str)) { str = BlockBlobDataManager.CreateUniqueDirectoryLoadBalanced(); } blockBlob = new BlockBlob() { AccountName = this._blob.AccountName, ContainerName = this._blob.ContainerName, BlobName = this._blob.BlobName, VersionTimestamp = DateTime.SpecifyKind(DateTime.MaxValue, DateTimeKind.Utc), DirectoryPath = str }; dbContext.Blobs.InsertOnSubmit(blockBlob); } StorageStampHelpers.ValidatePutBlobArguments(this, contentLength, null, applicationMetadata, contentMD5, sequenceNumberUpdate, overwriteOption, condition, true, false); byte[] byteArrayFromStream = DbStorageHelper.GetByteArrayFromStream(inputStream, out num, false, isLargeBlockBlobRequest); string file = BlockBlobDataManager.WriteBytesToFile(new BlockBlobMetaInfo(this._blob.AccountName, this._blob.ContainerName, this._blob.BlobName, str), byteArrayFromStream, out num1); Guid guid = Guid.NewGuid(); BlockData blockDatum = new BlockData() { AccountName = this._blob.AccountName, ContainerName = this._blob.ContainerName, BlobName = this._blob.BlobName, VersionTimestamp = this._blob.VersionTimestamp, IsCommitted = false, BlockId = DbListBlobObject.ToHexString(guid.ToByteArray()), FilePath = file, StartOffset = new long?(num1) }; dbContext.BlocksData.InsertOnSubmit(blockDatum); if (invokeGeneratePutBlobServiceMetadata && generatePutBlobServiceMetadata != null) { serviceMetadata = generatePutBlobServiceMetadata(); } blockBlob.ContentType = contentType ?? "application/octet-stream"; blockBlob.ContentMD5 = contentMD5; blockBlob.ServiceMetadata = serviceMetadata; blockBlob.Metadata = applicationMetadata; blockBlob.IsCommitted = new bool?(false); blockBlob.HasBlock = new bool?(false); blockBlob.UncommittedBlockIdLength = null; blockBlob.GenerationId = Guid.NewGuid().ToString(); blockBlob.SnapshotCount = 0; blockDatum.Length = new long?(num); blockBlob.ContentLength = num; base.ResetBlobLeaseToAvailable(blockBlob, flag); dbContext.SubmitChanges(); StringBuilder stringBuilder = new StringBuilder(); DbListBlobObject.SerializeCommitBlockListEntry(stringBuilder, guid.ToByteArray(), BlockSource.Uncommitted); DateTime?nullable = null; dbContext.CommitBlockList(this._blob.AccountName, this._blob.ContainerName, this._blob.BlobName, stringBuilder.ToString(), ref nullable); transactionScope.Complete(); blockBlob.LastModificationTime = nullable; this._blob = blockBlob; this.LeaseInfo = new BlobLeaseInfo(blockBlob, utcNow); } } }, base.Timeout, context.GetResumeCallback(), context.GetResumeState("DbListBlobObject.PutBlobImpl")); yield return(asyncResult); this._storageManager.AsyncProcessor.EndExecute(asyncResult); }
public IAsyncResult BeginSynchronousCopyBlob(string sourceAccount, IBlobObject sourceBlob, DateTime?expiryTime, byte[] applicationMetadata, OverwriteOption overwriteOption, IBlobObjectCondition sourceCondition, IBlobObjectCondition destinationCondition, UriString copySource, AsyncCallback callback, object state) { AsyncIteratorContext <CopyBlobOperationInfo> asyncIteratorContext = new AsyncIteratorContext <CopyBlobOperationInfo>("RealBlobObject.SynchronousCopyBlob", callback, state); asyncIteratorContext.Begin(this.SynchronousCopyBlobImpl(sourceAccount, sourceBlob, expiryTime, applicationMetadata, overwriteOption, sourceCondition, destinationCondition, copySource, asyncIteratorContext)); return(asyncIteratorContext); }
public ForegroundUploadOperation(LiveConnectClient client, Uri url, string filename, IFileSource inputFile, OverwriteOption option, IProgress <LiveOperationProgress> progress, SynchronizationContextWrapper syncContext) : base(client, url, ApiMethod.Upload, null, syncContext) { this.Filename = filename; this.Progress = progress; this.OverwriteOption = option; this.FileSource = inputFile; }
private void btnNoToAll_Click(object sender, EventArgs e) { overwriteOption_ = OverwriteOption.NoToAll; Close(); }
/// <summary> /// Create object with content /// </summary> /// <param name="locationid">Location id where you want to create object</param> /// <param name="name">Name of object</param> /// <param name="file">Object content</param> /// <param name="owoption">Overwrite option</param> /// <returns>Return created object</returns> public static T Create(T fileObject, Stream file, OverwriteOption overwriteOption) { return(Create(fileObject, file, overwriteOption, null)); }
private void btnYes_Click(object sender, EventArgs e) { overwriteOption_ = OverwriteOption.Yes; Close(); }
private IEnumerator <IAsyncResult> PutBlobImpl(string contentType, long contentLength, long?maxBlobSize, byte[] serviceMetadata, byte[] applicationMetadata, Stream inputStream, CrcReaderStream crcReaderStream, byte[] contentMD5, bool invokeGeneratePutBlobServiceMetadata, GeneratePutBlobServiceMetadata generatePutBlobServiceMetadata, bool isLargeBlockBlobRequest, bool is8TBPageBlobAllowed, ISequenceNumberUpdate sequenceNumberUpdate, OverwriteOption overwriteOption, IBlobObjectCondition condition, AsyncIteratorContext <NoResults> context) { IAsyncResult asyncResult; if (contentLength < (long)0) { throw new ArgumentOutOfRangeException("contentLength", "contentLength must be >= 0"); } try { asyncResult = this.blob.BeginPutBlob(contentType, contentLength, maxBlobSize, serviceMetadata, applicationMetadata, inputStream, crcReaderStream, contentMD5, invokeGeneratePutBlobServiceMetadata, generatePutBlobServiceMetadata, isLargeBlockBlobRequest, is8TBPageBlobAllowed, sequenceNumberUpdate, overwriteOption, Helpers.Convert(condition), context.GetResumeCallback(), context.GetResumeState("RealBlobObject.PutBlobImpl")); } catch (Exception exception) { StorageStamp.TranslateException(exception); throw; } yield return(asyncResult); try { this.blob.EndPutBlob(asyncResult); } catch (Exception exception1) { StorageStamp.TranslateException(exception1); throw; } }
private void btnYes_Click( object sender, EventArgs e ) { overwriteOption_ = OverwriteOption.Yes; Close(); }
/// <summary> /// Uploads a file into the OneDriveItem this command is called on. This command is only available on OneDriveItem instances that represents /// a folder or album. /// </summary> /// <param name="sourceItem"></param> /// <param name="option"></param> /// <param name="btp"></param> /// <param name="progress"></param> /// <returns></returns> public async Task<OneDriveItem> UploadFileAsync(IFileSource sourceItem, OverwriteOption option, IBackgroundTransferProvider btp = null, IProgress<LiveOperationProgress> progress = null) { if (this.ItemType != OneDriveItemType.Folder && this.ItemType != OneDriveItemType.Album) { throw new InvalidOperationException("Cannot upload files to items that do not represent a folder or album"); } LiveOperationResult result = await Client.LiveClient.UploadAsync( string.Format("/{0}", this.Identifier), sourceItem, option, btp, progress); System.Diagnostics.Debug.WriteLine("UploadFile Result: {0}", result.RawResult); FileUploadResult fur = FileUploadResult.FromJson(result.RawResult); return await this.Client.GetItemFromIdentifier(fur.Identifier); }
private void Copy(string fromFile, string toFile, long transferedSize) { if (!File.Exists(fromFile)) { throw new Exception("Input File " + fromFile + "Can't Opened."); } if (File.Exists(toFile)) { if (isNoOverwriteAll_) { return; } if (!isOverwriteAll_) { OverwritePrompt opWnd = new OverwritePrompt(); OverwriteOption owOp = opWnd.ExecuteDialog("File " + toFile + " was exists. Overwrite it?"); if (owOp == OverwriteOption.NoToAll) { isNoOverwriteAll_ = true; return; } if (owOp == OverwriteOption.No) { return; } if (owOp == OverwriteOption.YesToAll) { isOverwriteAll_ = true; } } } FileStream fin = null; FileStream fout = null; try { string outDirectory = Path.GetDirectoryName(toFile); if (!Directory.Exists(outDirectory)) { Directory.CreateDirectory(outDirectory); } fin = new FileStream(fromFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); fout = new FileStream(toFile, FileMode.Create, FileAccess.Write, FileShare.ReadWrite); int bufsize = 64 * 1024; // 64K Buffer byte[] buf = new byte[bufsize]; long curPos = 0; while (true) { if (isNeedExit_) { throw new Exception( "File copy was aborted by user." ); } int readCount = fin.Read(buf, 0, bufsize); fout.Write(buf, 0, readCount); curPos += readCount; //设置进度条和时间 pbTotal.Value = (int)((double)(curPos + transferedSize) / (double)totalSize_ * 1000.0); pbFile.Value = (int)((double)curPos / (double)fin.Length * 1000.0); int thisTick = Environment.TickCount; int elapsedTick = thisTick - startTick_; int totalTick = (int)((double)elapsedTick / (double)(curPos + transferedSize) * (double)totalSize_); TimeSpan ts = new TimeSpan(elapsedTick / 1000); elapsedTimeStr_ = ts.ToString(); ts = new TimeSpan(totalTick - elapsedTick); residualTimeStr_ = ts.ToString(); lblFilePercentage.Text = (pbFile.Value / 10).ToString() + "%"; lblTotalPercentage.Text = (pbTotal.Value / 10).ToString() + "%"; Application.DoEvents(); if (readCount < bufsize) { break; } } } catch (Exception exc) { if (fin != null) { fin.Close(); } if (fout != null) { fout.Close(); } try { File.Delete(toFile); } catch { ; //null } throw exc; } finally { fin.Close(); fout.Close(); FileInfo srcFileInfo = new FileInfo(fromFile); FileInfo toFileInfo = new FileInfo(toFile); toFileInfo.LastWriteTime = srcFileInfo.LastWriteTime; } }
private void btnNoToAll_Click( object sender, EventArgs e ) { overwriteOption_ = OverwriteOption.NoToAll; Close(); }
public Task <LiveOperationResult> UploadAsync(string path, IFileSource fileSource, OverwriteOption option, IBackgroundTransferProvider btu, CancellationToken ct, IProgress <LiveOperationProgress> progress) { if (string.IsNullOrEmpty(path)) { throw new ArgumentException( "path", String.Format(CultureInfo.CurrentUICulture, ResourceHelper.GetString("UrlInvalid"), "path")); } if (null == fileSource) { throw new ArgumentNullException( "fileSource", String.Format(CultureInfo.CurrentUICulture, ResourceHelper.GetString("InvalidNullParameter"), "fileSource")); } if (null != fileSource && string.IsNullOrEmpty(fileSource.Filename)) { throw new ArgumentException( "fileName", String.Format(CultureInfo.CurrentUICulture, ResourceHelper.GetString("InvalidNullOrEmptyParameter"), "fileName")); } if (null == btu) { btu = new Microsoft.Live.Transfers.BasicTransferProvider(); } ApiOperation op = btu.GetUploadOperation(this, this.GetResourceUri(path, ApiMethod.Upload), fileSource, option, progress, syncContext); return(this.ExecuteApiOperation(op, ct)); }
public async Task <FileInfo> UploadAsync(string parentFolderId, Stream content, string name, OverwriteOption overwrite = OverwriteOption.DoNotOverwrite, bool downsizePhotoUpload = false, bool checkForQuota = false) { if (checkForQuota) { var quota = await QuotaAsync(); if (quota.Available <= content.Length) { throw new NotEnoughQuotaException(); } } return(await Execute <FileInfo>(() => RequestGenerator.Upload(parentFolderId, name, content, overwrite, downsizePhotoUpload))); }
public IAsyncResult BeginPutBlob(string contentType, long contentLength, byte[] serviceMetadata, byte[] applicationMetadata, byte[][] blockList, BlockSource[] blockSourceList, byte[] contentMD5, OverwriteOption overwriteOption, IBlobObjectCondition condition, AsyncCallback callback, object state) { AsyncIteratorContext <NoResults> asyncIteratorContext = new AsyncIteratorContext <NoResults>("RealBlobObject.PutBlob", callback, state); asyncIteratorContext.Begin(this.PutBlobImpl(contentType, contentLength, serviceMetadata, applicationMetadata, blockList, blockSourceList, contentMD5, overwriteOption, condition, asyncIteratorContext)); return(asyncIteratorContext); }
/// <summary> /// Creates a background upload operation. /// </summary> /// <param name="path">relative or absolute uri to the location where the file should be uploaded to.</param> /// <param name="fileName">name for the uploaded file.</param> /// <param name="inputStream">Stream that contains the upload's content.</param> /// <param name="option">an enum to specify the overwrite behavior if a file with the same name already exists.</param> /// <returns>A Task object representing the asynchronous operation.</returns> public Task<LiveUploadOperation> CreateBackgroundUploadAsync( string path, string fileName, IInputStream inputStream, OverwriteOption option) { if (string.IsNullOrEmpty(path)) { throw new ArgumentException( "path", String.Format(CultureInfo.CurrentUICulture, ResourceHelper.GetString("UrlInvalid"), "path")); } if (string.IsNullOrEmpty(fileName)) { throw new ArgumentException( "fileName", String.Format(CultureInfo.CurrentUICulture, ResourceHelper.GetString("InvalidNullOrEmptyParameter"), "fileName")); } if (inputStream == null) { throw new ArgumentNullException( "inputStream", String.Format(CultureInfo.CurrentUICulture, ResourceHelper.GetString("InvalidNullParameter"), "inputStream")); } var op = new CreateBackgroundUploadOperation( this, this.GetResourceUri(path, ApiMethod.Upload), fileName, inputStream, option); return op.ExecuteAsync(); }
public IAsyncResult BeginPutBlob(string contentType, long contentLength, long?maxBlobSize, byte[] serviceMetadata, byte[] applicationMetadata, Stream inputStream, CrcReaderStream crcReaderStream, byte[] contentMD5, bool invokeGeneratePutBlobServiceMetadata, GeneratePutBlobServiceMetadata generatePutBlobServiceMetadata, bool isLargeBlockBlobRequest, bool is8TBPageBlobAllowed, ISequenceNumberUpdate sequenceNumberUpdate, OverwriteOption overwriteOption, IBlobObjectCondition condition, AsyncCallback callback, object state) { AsyncIteratorContext <NoResults> asyncIteratorContext = new AsyncIteratorContext <NoResults>("RealBlobObject.PutBlob", callback, state); asyncIteratorContext.Begin(this.PutBlobImpl(contentType, contentLength, maxBlobSize, serviceMetadata, applicationMetadata, inputStream, crcReaderStream, contentMD5, invokeGeneratePutBlobServiceMetadata, generatePutBlobServiceMetadata, isLargeBlockBlobRequest, is8TBPageBlobAllowed, sequenceNumberUpdate, overwriteOption, condition, asyncIteratorContext)); return(asyncIteratorContext); }
public static void ValidatePutBlobArguments(IBlobObject blob, long contentLength, long?maxBlobSize, byte[] applicationMetadata, byte[] contentMD5, ISequenceNumberUpdate sequenceNumberUpdate, OverwriteOption overwriteOption, IBlobObjectCondition condition, bool isLargeBlockBlobRequest, bool is8TBPageBlobAllowed) { if (blob.Snapshot != StorageStampHelpers.RootBlobSnapshotVersion) { throw new XStoreArgumentException("This operation is only supported on the root blob."); } long num = 1099511627776L; if (contentLength < (long)0) { throw new ArgumentOutOfRangeException("contentLength", "contentLength must be >= 0"); } if (blob.Type == BlobType.ListBlob && !isLargeBlockBlobRequest && contentLength > (long)67108864) { throw new BlobContentTooLargeException(new long?((long)67108864), null, null); } if (blob.Type == BlobType.IndexBlob && maxBlobSize.Value > num) { throw new BlobContentTooLargeException(new long?(num), null, null); } StorageStampHelpers.ValidateMaxBlobSizeForPutBlob(blob, maxBlobSize); StorageStampHelpers.ValidateApplicationMetadata(applicationMetadata); if (contentMD5 != null && (long)((int)contentMD5.Length) != (long)16) { throw new MD5InvalidException(); } if (sequenceNumberUpdate != null) { if (blob.Type != BlobType.IndexBlob) { throw new XStoreArgumentException("sequenceNumberUpdate only allowed for PageBlob"); } if (sequenceNumberUpdate.UpdateType != SequenceNumberUpdateType.Update) { throw new XStoreArgumentException("sequenceNumberUpdate can only have type Update for PutBlob."); } if (sequenceNumberUpdate.SequenceNumber < (long)0 || sequenceNumberUpdate.SequenceNumber > 9223372036854775807L) { throw new XStoreArgumentException("sequenceNumberUpdate sequence number must be >= 0 and < Int64.MaxValue."); } } }
/// <summary> /// Uploads a file to the given path using the Windows Phone BackgroundTransferService. /// </summary> /// <param name="path">The path to the folder to upload the file to.</param> /// <param name="uploadLocation">The location of the file on the device to upload.</param> /// <param name="option">an enum to specify the overwrite behavior if a file with the same name already exists.</param> /// <param name="ct">a token that is used to cancel the background upload operation.</param> /// <param name="progress">an object that is called to report the background upload's progress.</param> /// <returns>A Task object representing the asynchronous operation.</returns> public Task<LiveOperationResult> BackgroundUploadAsync( string path, Uri uploadLocation, OverwriteOption option, CancellationToken ct, IProgress<LiveOperationProgress> progress) { if (path == null) { string message = String.Format(CultureInfo.CurrentUICulture, ResourceHelper.GetString("UrlInvalid"), "path"); throw new ArgumentNullException("path", message); } if (uploadLocation == null) { throw new ArgumentNullException("uploadLocation"); } string filename = Path.GetFileName(uploadLocation.OriginalString); if (string.IsNullOrEmpty(filename)) { string message = String.Format(CultureInfo.CurrentUICulture, ResourceHelper.GetString("UriMissingFileName"), "uploadLocation"); throw new ArgumentException(message, "uploadLocation"); } if (!BackgroundTransferHelper.IsRootedInSharedTransfers(uploadLocation)) { string message = String.Format(CultureInfo.CurrentUICulture, ResourceHelper.GetString("UriMustBeRootedInSharedTransfers"), "uploadLocation"); throw new ArgumentException(message, "uploadLocation"); } var builder = new BackgroundUploadOperation.Builder { BackgroundTransferService = this.BackgroundTransferService, Client = this, Path = path, UploadLocationOnDevice = uploadLocation, OverwriteOption = option, Progress = progress, BackgroundTransferPreferences = this.BackgroundTransferPreferences }; BackgroundUploadOperation operation = builder.Build(); ct.Register(operation.Cancel); return operation.ExecuteAsync(); }
/// <summary> /// Upload a file to the server. /// </summary> /// <param name="path">relative or absolute uri to the location where the file should be uploaded to.</param> /// <param name="fileName">name for the uploaded file.</param> /// <param name="inputStream">Stream that contains the file content.</param> /// <param name="option"> /// a enum to specify the overwrite behavior if a file with the same name already exists. /// Default is DoNotOverwrite. /// </param> /// <param name="ct">a cancellation token</param> /// <param name="progress">a progress event callback handler</param> public Task<LiveOperationResult> UploadAsync( string path, string fileName, Stream inputStream, OverwriteOption option, CancellationToken ct, IProgress<LiveOperationProgress> progress) { LiveUtility.ValidateNotNullOrWhiteSpaceString(path, "path"); LiveUtility.ValidateNotNullParameter(inputStream, "inputStream"); if (string.IsNullOrEmpty(fileName)) { string message = String.Format(CultureInfo.CurrentUICulture, ResourceHelper.GetString("InvalidNullOrEmptyParameter"), "fileName"); throw new ArgumentException(message, "fileName"); } if (!inputStream.CanRead) { string message = String.Format(CultureInfo.CurrentUICulture, ResourceHelper.GetString("StreamNotReadable"), "inputStream"); throw new ArgumentException(message, "inputStream"); } if (this.Session == null) { throw new LiveConnectException(ApiOperation.ApiClientErrorCode, ResourceHelper.GetString("UserNotLoggedIn")); } var tcs = new TaskCompletionSource<LiveOperationResult>(); var op = new UploadOperation( this, this.GetResourceUri(path, ApiMethod.Upload), fileName, inputStream, option, progress, null); op.OperationCompletedCallback = (LiveOperationResult result) => { if (result.IsCancelled) { tcs.TrySetCanceled(); } else if (result.Error != null) { tcs.TrySetException(result.Error); } else { tcs.TrySetResult(result); } }; ct.Register(op.Cancel); op.Execute(); return tcs.Task; }
/// <summary> /// Upload a file to the server. /// </summary> /// <param name="path">relative or absolute uri to the location where the file should be uploaded to.</param> /// <param name="fileName">name for the uploaded file.</param> /// <param name="inputStream">Stream that contains the file content.</param> /// <param name="option">an enum to specify the overwrite behavior if a file with the same name already exists.</param> /// <param name="ct">a token that is used to cancel the upload operation.</param> /// <param name="progress">an object that is called to report the upload's progress.</param> /// <returns>A Task object representing the asynchronous operation.</returns> public Task<LiveOperationResult> UploadAsync( string path, string fileName, Stream inputStream, OverwriteOption option, CancellationToken ct, IProgress<LiveOperationProgress> progress) { if (string.IsNullOrEmpty(path)) { string message = String.Format(CultureInfo.CurrentUICulture, ResourceHelper.GetString("UrlInvalid"), "path"); throw new ArgumentException(message, "path"); } if (string.IsNullOrEmpty(fileName)) { string message = String.Format(CultureInfo.CurrentUICulture, ResourceHelper.GetString("InvalidNullOrEmptyParameter"), "fileName"); throw new ArgumentException(message, "fileName"); } if (inputStream == null) { string message = String.Format(CultureInfo.CurrentUICulture, ResourceHelper.GetString("InvalidNullParameter"), "inputStream"); throw new ArgumentNullException("inputStream", message); } if (!inputStream.CanRead) { string message = String.Format(CultureInfo.CurrentUICulture, ResourceHelper.GetString("StreamNotReadable"), "inputStream"); throw new ArgumentException(message, "inputStream"); } var operation = new UploadOperation( this, this.GetResourceUri(path, ApiMethod.Upload), fileName, inputStream, option, progress != null ? new Action<LiveOperationProgress>(progress.Report) : null, SynchronizationContextWrapper.Current); return this.ExecuteApiOperation(operation, ct); }
/// <summary> /// Upload a stream to the server. /// </summary> /// <param name="path">relative or absolute uri to the location where the file should be uploaded to.</param> /// <param name="fileName">name for the uploaded file.</param> /// <param name="inputStream">Stream that contains the upload's content.</param> /// <param name="option">an enum to specify the overwrite behavior if a file with the same name already exists.</param> /// <param name="ct">a token that is used to cancel the upload operation.</param> /// <param name="progress">an object that is called to report the upload's progress.</param> /// <returns>A Task object representing the asynchronous operation.</returns> public Task<LiveOperationResult> BackgroundUploadAsync( string path, string fileName, IInputStream inputStream, OverwriteOption option, CancellationToken ct, IProgress<LiveOperationProgress> progress) { if (string.IsNullOrEmpty(path)) { throw new ArgumentException( "path", String.Format(CultureInfo.CurrentUICulture, ResourceHelper.GetString("UrlInvalid"), "path")); } if (string.IsNullOrEmpty(fileName)) { throw new ArgumentException( "fileName", String.Format(CultureInfo.CurrentUICulture, ResourceHelper.GetString("InvalidNullOrEmptyParameter"), "fileName")); } if (inputStream == null) { throw new ArgumentNullException( "inputStream", String.Format(CultureInfo.CurrentUICulture, ResourceHelper.GetString("InvalidNullParameter"), "inputStream")); } ApiOperation op = new TailoredUploadOperation( this, this.GetResourceUri(path, ApiMethod.Upload), fileName, inputStream, option, progress, null); return this.ExecuteApiOperation(op, ct); }
public IAsyncResult BeginAsynchronousCopyBlob(UriString copySource, bool isSourceAzureBlob, FECopyType copyType, long contentLength, string contentType, NameValueCollection serviceMetadataCollection, byte[] applicationMetadata, ISequenceNumberUpdate sequenceNumberUpdate, OverwriteOption overwriteOption, string sourceETag, IBlobObjectCondition destinationCondition, AsyncCallback callback, object state) { AsyncIteratorContext <CopyBlobOperationInfo> asyncIteratorContext = new AsyncIteratorContext <CopyBlobOperationInfo>("RealBlobObject.AsynchronousCopyBlob", callback, state); asyncIteratorContext.Begin(this.AsynchronousCopyBlobImpl(copySource, isSourceAzureBlob, copyType, contentLength, contentType, serviceMetadataCollection, applicationMetadata, sequenceNumberUpdate, overwriteOption, sourceETag, destinationCondition, asyncIteratorContext)); return(asyncIteratorContext); }
public Task<LiveOperationResult> UploadAsync(string path, IFileSource fileSource, OverwriteOption option, IBackgroundTransferProvider btu = null, IProgress<LiveOperationProgress> progress = null) { return this.UploadAsync(path, fileSource, option, btu, new CancellationToken(false), progress); }
private IEnumerator <IAsyncResult> AsynchronousCopyBlobImpl(UriString copySource, bool isSourceAzureBlob, FECopyType copyType, long contentLength, string contentType, NameValueCollection serviceMetadataCollection, byte[] applicationMetadata, ISequenceNumberUpdate sequenceNumberUpdate, OverwriteOption overwriteOption, string sourceETag, IBlobObjectCondition destinationCondition, AsyncIteratorContext <CopyBlobOperationInfo> context) { IAsyncResult asyncResult; try { asyncResult = this.blob.BeginAsynchronousCopyBlob(copySource, isSourceAzureBlob, copyType, contentLength, contentType, serviceMetadataCollection, applicationMetadata, sequenceNumberUpdate, overwriteOption, sourceETag, Helpers.Convert(destinationCondition), context.GetResumeCallback(), context.GetResumeState("IBlobObject.BeginAsynchronousCopyBlob")); } catch (Exception exception) { StorageStamp.TranslateException(exception); throw; } yield return(asyncResult); CopyBlobOperationInfo copyBlobOperationInfo = null; try { copyBlobOperationInfo = this.blob.EndAsynchronousCopyBlob(asyncResult); } catch (Exception exception1) { StorageStamp.TranslateException(exception1); throw; } context.ResultData = copyBlobOperationInfo; }
public IRequest Upload(string parentFolderId, string name, Stream content, OverwriteOption overwrite = OverwriteOption.Overwrite, bool downsizePhotoUpload = false) { string resource = string.IsNullOrWhiteSpace(parentFolderId) ? "me/skydrive/files/" + name : parentFolderId + "/files/" + name; Request request = ContentRequest(HttpMethod.Put, ContentUrlBase, resource); request.AddParameter("overwrite", overwrite.GetDescription()); request.AddParameter("downsize_photo_uploads", downsizePhotoUpload.ToString()); if (content.CanSeek) content.Position = 0; request.Content = new CompressedContent(new StreamContent(content, 64 * 1024), "gzip"); return request; }
private IEnumerator <IAsyncResult> SynchronousCopyBlobImpl(string sourceAccount, IBlobObject sourceBlob, DateTime?expiryTime, byte[] applicationMetadata, OverwriteOption overwriteOption, IBlobObjectCondition sourceCondition, IBlobObjectCondition destinationCondition, UriString copySource, AsyncIteratorContext <CopyBlobOperationInfo> context) { IAsyncResult asyncResult; try { asyncResult = this.blob.BeginSynchronousCopyBlob(sourceAccount, ((BaseBlobObject)sourceBlob).blob, StorageStampHelpers.AdjustNullableDatetimeRange(expiryTime), applicationMetadata, overwriteOption, Helpers.Convert(sourceCondition), Helpers.Convert(destinationCondition), copySource, context.GetResumeCallback(), context.GetResumeState("IBlobObject.BeginSynchronousCopyBlob")); } catch (Exception exception) { StorageStamp.TranslateException(exception); throw; } yield return(asyncResult); CopyBlobOperationInfo copyBlobOperationInfo = null; try { copyBlobOperationInfo = this.blob.EndSynchronousCopyBlob(asyncResult); } catch (Exception exception1) { StorageStamp.TranslateException(exception1); throw; } context.ResultData = copyBlobOperationInfo; }
private BackgroundUploadOperation(Builder builder) { this.path = builder.Path; this.uploadLocationOnDevice = builder.UploadLocationOnDevice; this.client = builder.Client; this.backgroundTransferService = builder.BackgroundTransferService; this.overwriteOption = builder.OverwriteOption; this.progress = builder.Progress; this.tcs = new TaskCompletionSource<LiveOperationResult>(); this.requestAddedToService = false; this.status = OperationStatus.NotStarted; this.transferPreferences = BackgroundTransferHelper.GetTransferPreferences(builder.BackgroundTransferPreferences); }
/// <summary> /// Upload a file to the server. /// </summary> /// <param name="path">relative or absolute uri to the location where the file should be uploaded to.</param> /// <param name="fileName">name for the uploaded file.</param> /// <param name="inputStream">Stream that contains the file content.</param> /// <param name="option"> /// a enum to specify the overwrite behavior if a file with the same name already exists. /// Default is DoNotOverwrite. /// </param> /// <param name="ct">a cancellation token</param> /// <param name="progress">a progress event callback handler</param> public Task <LiveOperationResult> UploadAsync( string path, string fileName, Stream inputStream, OverwriteOption option, CancellationToken ct, IProgress <LiveOperationProgress> progress) { LiveUtility.ValidateNotNullOrWhiteSpaceString(path, "path"); LiveUtility.ValidateNotNullParameter(inputStream, "inputStream"); if (string.IsNullOrEmpty(fileName)) { string message = String.Format(CultureInfo.CurrentUICulture, ResourceHelper.GetString("InvalidNullOrEmptyParameter"), "fileName"); throw new ArgumentException(message, "fileName"); } if (!inputStream.CanRead) { string message = String.Format(CultureInfo.CurrentUICulture, ResourceHelper.GetString("StreamNotReadable"), "inputStream"); throw new ArgumentException(message, "inputStream"); } if (this.Session == null) { throw new LiveConnectException(ApiOperation.ApiClientErrorCode, ResourceHelper.GetString("UserNotLoggedIn")); } var tcs = new TaskCompletionSource <LiveOperationResult>(); var op = new UploadOperation( this, this.GetResourceUri(path, ApiMethod.Upload), fileName, inputStream, option, progress, null); op.OperationCompletedCallback = (LiveOperationResult result) => { if (result.IsCancelled) { tcs.TrySetCanceled(); } else if (result.Error != null) { tcs.TrySetException(result.Error); } else { tcs.TrySetResult(result); } }; ct.Register(op.Cancel); op.Execute(); return(tcs.Task); }
public Task <LiveOperationResult> UploadAsync(string path, IFileSource fileSource, OverwriteOption option, IBackgroundTransferProvider btu = null, IProgress <LiveOperationProgress> progress = null) { return(this.UploadAsync(path, fileSource, option, btu, new CancellationToken(false), progress)); }
public async Task<SkyDriveFile> UploadFileAsync(StorageFile file, string skyDriveFileName = null, OverwriteOption overwrite = OverwriteOption.DoNotOverwrite) { LiveOperationResult result = await this.CxnClient.BackgroundUploadAsync(this.Id, string.IsNullOrEmpty(skyDriveFileName) ? file.Name : skyDriveFileName, file, overwrite); this.MarkStale(); return (new SkyDriveFile(this.CxnClient, result.Result)); }
private IEnumerator <IAsyncResult> PutBlobImpl(string contentType, long contentLength, byte[] serviceMetadata, byte[] applicationMetadata, byte[][] blockIdList, BlockSource[] blockSourceList, byte[] contentMD5, OverwriteOption overwriteOption, IBlobObjectCondition condition, AsyncIteratorContext <NoResults> context) { IAsyncResult asyncResult; bool flag = contentLength == (long)-1; object[] objArray = new object[] { contentLength }; NephosAssertionException.Assert(flag, "The contentLength we are going to pass into XStore for commiting blob is invalid: {0}", objArray); try { asyncResult = ((IListBlobObject)this.blob).BeginPutBlob(contentType, contentLength, serviceMetadata, applicationMetadata, blockIdList, blockSourceList, contentMD5, overwriteOption, Helpers.Convert(condition), context.GetResumeCallback(), context.GetResumeState("RealBlobObject.PutBlobImpl")); } catch (Exception exception) { StorageStamp.TranslateException(exception); throw; } yield return(asyncResult); try { this.blob.EndPutBlob(asyncResult); } catch (Exception exception1) { StorageStamp.TranslateException(exception1); throw; } }
/// <summary> /// Uploads a file to the given path using the Windows Phone BackgroundTransferService. /// </summary> /// <param name="path">The path to the folder to upload the file to.</param> /// <param name="uploadLocation">The location of the file on the device to upload.</param> /// <param name="option">an enum to specify the overwrite behavior if a file with the same name already exists.</param> /// <returns>A Task object representing the asynchronous operation.</returns> public Task<LiveOperationResult> BackgroundUploadAsync( string path, Uri uploadLocation, OverwriteOption option) { return this.BackgroundUploadAsync(path, uploadLocation, option, new CancellationToken(false), null); }
public static string GetOverwriteValue(OverwriteOption option) { return(uploadOptionToOverwriteValue[option]); }
public ApiOperation GetUploadOperation(LiveConnectClient client, Uri url, IFileSource inputFile, OverwriteOption option, IProgress<LiveOperationProgress> progress, SynchronizationContextWrapper syncContext) { return new UploadOperation(client, url, inputFile.Filename, inputFile.GetReadStream(), option, progress, syncContext); }