internal UploadManager(IUploaderFactory uploaderFactory, UploadOperation uploadOperation)
    {
        var uploader = uploaderFactory.GetUploader(uploadOperation);

        //run different set of async tasks based on OperationType,
        //using nested class Uploader
        uploader.DoStuff();
    }
Пример #2
0
        /// <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");
            }

            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);
        }
Пример #3
0
        private async void StartMultipartUpload_Click(object sender, RoutedEventArgs e)
        {
            // By default 'serverAddressField' is disabled and URI validation is not required. When enabling the text
            // box validating the URI is required since it was received from an untrusted source (user input).
            // The URI is validated by calling Uri.TryCreate() that will return 'false' for strings that are not valid URIs.
            // Note that when enabling the text box users may provide URIs to machines on the intrAnet that require
            // the "Home or Work Networking" capability.
            Uri uri;

            if (!Uri.TryCreate(serverAddressField.Text.Trim(), UriKind.Absolute, out uri))
            {
                rootPage.NotifyUser("Invalid URI.", NotifyType.ErrorMessage);
                return;
            }

            // Verify that we are currently not snapped, or that we can unsnap to open the picker.
            if (ApplicationView.Value == ApplicationViewState.Snapped && !ApplicationView.TryUnsnap())
            {
                rootPage.NotifyUser("File picker cannot be opened in snapped mode. Please unsnap first.", NotifyType.ErrorMessage);
                return;
            }

            FileOpenPicker picker = new FileOpenPicker();

            picker.FileTypeFilter.Add("*");
            IReadOnlyList <StorageFile> files = await picker.PickMultipleFilesAsync();

            if (files.Count == 0)
            {
                rootPage.NotifyUser("No file selected.", NotifyType.ErrorMessage);
                return;
            }

            List <BackgroundTransferContentPart> parts = new List <BackgroundTransferContentPart>();

            for (int i = 0; i < files.Count; i++)
            {
                BackgroundTransferContentPart part = new BackgroundTransferContentPart("File" + i, files[i].Name);
                part.SetFile(files[i]);
                parts.Add(part);
            }

            BackgroundUploader uploader = new BackgroundUploader();
            UploadOperation    upload   = await uploader.CreateUploadAsync(uri, parts);

            String fileNames = files[0].Name;

            for (int i = 1; i < files.Count; i++)
            {
                fileNames += ", " + files[i].Name;
            }

            Log(String.Format("Uploading {0} to {1}, {2}", fileNames, uri.AbsoluteUri, upload.Guid));

            // Attach progress and completion handlers.
            await HandleUploadAsync(upload, true);
        }
        public void AddUploadOperation(UploadOperation uploadOperation)
        {
            var entry = new BucketEntryViewModel(this, _bucketService, _objectService);

            entry.IsUploadOperation = true;
            entry.UploadOperation   = uploadOperation;
            entry.InitUploadOperation();
            Entries.Add(entry);
        }
Пример #5
0
 public static HttpTransfer FromNative(this UploadOperation x) => new HttpTransfer(
     x.Guid.ToString(),
     x.RequestedUri.ToString(),
     x.SourceFile.Path,
     true,
     x.CostPolicy == BackgroundTransferCostPolicy.Always,
     null,
     (long)x.Progress.TotalBytesToSend,
     (long)x.Progress.BytesSent,
     x.Progress.Status.FromNative()
     );
Пример #6
0
 private async Task OnUploadProgressChanged(UploadOperation obj)
 {
     if (Windows.ApplicationModel.Core.CoreApplication.Views.Count > 0)
     {
         await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
         {
             ExecutionContext.Instance.BackgroundTransferOperation = obj;
             ExecutionContext.Instance.Status = ExecutionStatus.Sending;
         });
     }
 }
Пример #7
0
 private void OnUploadProgressChanged(UploadOperation e, ICompletedUpload upload)
 {
     ProgressChanged?.Invoke(this, new TransferItem
     {
         OperationGuid = e.Guid,
         Name          = upload.Name,
         ContentType   = upload.ContentType,
         Status        = e.Progress.Status,
         TotalSize     = FileSize.FromBytes(e.Progress.TotalBytesToSend),
         ProcessedSize = FileSize.FromBytes(e.Progress.BytesSent)
     });
 }
Пример #8
0
        public void NapackUploadOperationFailsWhenUserNotRegistered()
        {
            UploadOperation uploadOperation = new UploadOperation()
            {
                Operation = "Upload",
                ForceMajorUpversioning = false,
                ForceMinorUpversioning = false,
                PackageFile            = NapackOperationTests.PackageJsonFileLocation,
                NapackSettingsFile     = NapackOperationTests.SettingsFileLocation
            };

            uploadOperation.PerformOperation();
        }
Пример #9
0
        /// <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));
        }
Пример #10
0
        public async Task <UploadOperation> UploadObjectAsync(Bucket bucket, string targetPath, UploadOptions uploadOptions, byte[] bytesToUpload, CustomMetadata customMetadata, bool immediateStart = true)
        {
            var uploadOptionsSWIG = uploadOptions.ToSWIG();

            SWIG.UploadResult uploadResult = await Task.Run(() => SWIG.storj_uplink.upload_object(_access._project, bucket.Name, targetPath, uploadOptionsSWIG));

            UploadOperation upload = new UploadOperation(bytesToUpload, uploadResult, targetPath, customMetadata);

            if (immediateStart)
            {
                upload.StartUploadAsync(); //Don't await it, otherwise it would "block" UploadObjectAsync
            }
            return(upload);
        }
        public async Task <string> CreateVideoAsync(IStorageFile file, Video v)
        {
            VideoSubmition videoSubmition = new VideoSubmition
            {
                Tags    = v.Tags,
                Title   = v.Title,
                Synopse = v.Synopse
            };

            Video createdVideo = null;

            try
            {
                using (EnsureCredentialsUseContext context = new EnsureCredentialsUseContext(
                           this.Username, this.Password, this.AccessKey, _client.InnerChannel))
                {
                    createdVideo = await this._client.AddVideoPostAsync(videoSubmition, null);
                }
            }
            catch (FaultException faultException)
            {
                MessageFault messageFault = faultException.CreateMessageFault();

                if (messageFault.HasDetail)
                {
                    string innerErrorXml;
                    using (var xmlReader = messageFault.GetReaderAtDetailContents())
                    {
                        innerErrorXml = xmlReader.ReadInnerXml();
                    }
                    if (innerErrorXml != null)
                    {
                        throw new Exception(innerErrorXml);
                    }
                    throw;
                }
            }

            string token = createdVideo.Token;

            BackgroundUploader uploader = new BackgroundUploader();

            UploadOperation uploadOperation =
                await VideosServiceClient.CreateUploadOperationForCreateVideo(file, token, uploader);

            await uploadOperation.StartAsync();

            return(await GetResponseMessage(uploadOperation));
        }
Пример #12
0
        private async void UploadMultipleFiles(Uri uri, IReadOnlyList <StorageFile> files)
        {
            if (files.Count == 0)
            {
                rootPage.NotifyUser("No file selected.", NotifyType.ErrorMessage);
                return;
            }

            ulong totalFileSize = 0;

            for (int i = 0; i < files.Count; i++)
            {
                BasicProperties properties = await files[i].GetBasicPropertiesAsync();
                totalFileSize += properties.Size;

                if (totalFileSize > maxUploadFileSize)
                {
                    rootPage.NotifyUser(String.Format(CultureInfo.CurrentCulture,
                                                      "Size of selected files exceeds max. upload file size ({0} MB).",
                                                      maxUploadFileSize / (1024 * 1024)), NotifyType.ErrorMessage);
                    return;
                }
            }

            List <BackgroundTransferContentPart> parts = new List <BackgroundTransferContentPart>();

            for (int i = 0; i < files.Count; i++)
            {
                BackgroundTransferContentPart part = new BackgroundTransferContentPart("File" + i, files[i].Name);
                part.SetFile(files[i]);
                parts.Add(part);
            }

            BackgroundUploader uploader = new BackgroundUploader();
            UploadOperation    upload   = await uploader.CreateUploadAsync(uri, parts);

            String fileNames = files[0].Name;

            for (int i = 1; i < files.Count; i++)
            {
                fileNames += ", " + files[i].Name;
            }

            Log(String.Format(CultureInfo.CurrentCulture, "Uploading {0} to {1}, {2}", fileNames, uri.AbsoluteUri,
                              upload.Guid));

            // Attach progress and completion handlers.
            await HandleUploadAsync(upload, true);
        }
Пример #13
0
        /// <summary>
        /// Invoked when image add button is clicked and choose the image.
        /// </summary>
        /// <param name="sender">The image add button clicked.</param>
        /// <param name="e">Event data that describes how the click was initiated.</param>
        private async void ImageUploadButton_Click(object sender, RoutedEventArgs e)
        {
            FileOpenPicker picker = FileTypePicker(imagesFilterTypeList);

            if (picker == null)
            {
                return;
            }

            images = await picker.PickMultipleFilesAsync();

            if (images == null || images.Count == 0)
            {
                return;
            }

            Image imgImg = new Image
            {
                Source = new BitmapImage(new Uri("ms-appx:///Images/Upload/image.png")),
                Margin = new Thickness(5, 0, 5, 0)
            };

            ToolTip toolTip = new ToolTip();

            toolTip.Content = images[0].Name;
            ToolTipService.SetToolTip(imgImg, toolTip);

            totalImagePanel.Children.RemoveAt(totalImagePanel.Children.Count - 1);
            imagePanel.Children.Add(imgImg);

            List <BackgroundTransferContentPart> imageParts = CreateBackgroundTransferContentPartList(images);

            Uri uploadUri = new Uri(Constants.DataCenterURI + "Upload.aspx?username="******"Image uplaod error3. Please check your network.");
            }
        }
        public async Task UploadAsync(StorageFile file, int travelerId, Progress <UploadOperation> progressCallback, int reservationId, bool isPrivate)
        {
            var address     = isPrivate ? Addresses.UploadPrivateFileUri : Addresses.UploadPublicFileUri;
            Uri destination = new Uri(string.Format(address, reservationId));

            BackgroundUploader uploader = new BackgroundUploader();

            uploader.SetRequestHeader("Filename", file.Name);
            UploadOperation upload = uploader.CreateUpload(destination, file);

            UploadOperation result = await upload.StartAsync().AsTask();

            string fileUri = result.GetResponseInformation().Headers["Location"];
            await _data.CreateAzureStorageFileMetadata(fileUri, file.Name, reservationId, isPrivate, UserAuth.Instance.Traveler.TravelerId);
        }
Пример #15
0
        public async Task UploadAsync(StorageFile sourceFile, int travelerId, int reservationId, bool isPrivate, int locationId)
        {
            var address        = isPrivate ? Addresses.UploadPrivateFileUri : Addresses.UploadPublicFileUri;
            Uri destinationUri = new Uri(string.Format(address, reservationId));

            BackgroundUploader uploader = new BackgroundUploader();

            uploader.SetRequestHeader("Filename", sourceFile.Name);
            UploadOperation upload = uploader.CreateUpload(destinationUri, sourceFile);
            await upload.StartAsync();

            var fileAddress = upload.GetResponseInformation().Headers["Location"];

            await _data.CreateAzureStorageFileMetadata(new Uri(fileAddress), sourceFile.Name, reservationId, isPrivate, travelerId, locationId);
        }
 /// <summary>
 /// This is the upload handler.
 /// </summary>
 /// <param name="upload"></param>
 /// <param name="start"></param>
 private static async void HandleUploadAsync(UploadOperation upload, bool start)
 {
     try
     {
         Progress <UploadOperation> progressCallback = new Progress <UploadOperation>(UploadProgress);
         if (start)
         {
             await upload.StartAsync().AsTask(cancellationToken.Token, progressCallback);
         }
         ResponseInformation response = upload.GetResponseInformation();
     }
     catch (Exception ex)
     {
     }
 }
Пример #17
0
        private const int maxUploadFileSize = 100 * 1024 * 1024; // 100 MB

        /// <summary>
        /// StartUploadFiles
        /// </summary>
        /// <param name="url"></param>
        /// <param name="files"></param>
        public async void StartUploadFiles(string url, IReadOnlyList <StorageFile> files)
        {
            Uri uri = null;

            if (!Uri.TryCreate(url, UriKind.Absolute, out uri))
            {
                if (this.ErrorException != null)
                {
                    this.ErrorException(this, "Please Invalid UploadURl");
                }
                return;
            }
            if (files == null || files.Count == 0)
            {
                if (this.ErrorException != null)
                {
                    this.ErrorException(this, "Please Invalid files");
                }
                return;
            }
            ulong totalFileSize = 0;

            for (int i = 0; i < files.Count; i++)
            {
                BasicProperties properties = await files[i].GetBasicPropertiesAsync();
                totalFileSize += properties.Size;
                if (totalFileSize > maxUploadFileSize)
                {
                    if (this.ErrorException != null)
                    {
                        this.ErrorException(this, "Please Invalid maxUploadFileSize");
                    }
                    return;
                }
            }
            List <BackgroundTransferContentPart> parts = new List <BackgroundTransferContentPart>();

            for (int i = 0; i < files.Count; i++)
            {
                BackgroundTransferContentPart part = new BackgroundTransferContentPart("File" + i, files[i].Name);
                part.SetFile(files[i]);
                parts.Add(part);
            }
            BackgroundUploader uploader = new BackgroundUploader();
            UploadOperation    upload   = await uploader.CreateUploadAsync(uri, parts);

            await HandleUploadAsync(upload, true);
        }
Пример #18
0
        private async void StartUpload_Click(object sender, RoutedEventArgs e)
        {
            // By default 'serverAddressField' is disabled and URI validation is not required. When enabling the text
            // box validating the URI is required since it was received from an untrusted source (user input).
            // The URI is validated by calling Uri.TryCreate() that will return 'false' for strings that are not valid URIs.
            // Note that when enabling the text box users may provide URIs to machines on the intrAnet that require
            // the "Home or Work Networking" capability.
            Uri uri;

            if (!Uri.TryCreate(serverAddressField.Text.Trim(), UriKind.Absolute, out uri))
            {
                rootPage.NotifyUser("Invalid URI.", NotifyType.ErrorMessage);
                return;
            }

            FileOpenPicker picker = new FileOpenPicker();

            picker.FileTypeFilter.Add("*");
            StorageFile file = await picker.PickSingleFileAsync();

            if (file == null)
            {
                rootPage.NotifyUser("No file selected.", NotifyType.ErrorMessage);
                return;
            }

            BasicProperties properties = await file.GetBasicPropertiesAsync();

            if (properties.Size > maxUploadFileSize)
            {
                rootPage.NotifyUser(String.Format(CultureInfo.CurrentCulture,
                                                  "Selected file exceeds max. upload file size ({0} MB).", maxUploadFileSize / (1024 * 1024)),
                                    NotifyType.ErrorMessage);
                return;
            }

            BackgroundUploader uploader = new BackgroundUploader();

            uploader.SetRequestHeader("Filename", file.Name);

            UploadOperation upload = uploader.CreateUpload(uri, file);

            Log(String.Format(CultureInfo.CurrentCulture, "Uploading {0} to {1}, {2}", file.Name, uri.AbsoluteUri,
                              upload.Guid));

            // Attach progress and completion handlers.
            await HandleUploadAsync(upload, true);
        }
Пример #19
0
        public async Task <UploadOperation> UploadObjectAsync(Bucket bucket, string targetPath, UploadOptions uploadOptions, Stream stream, CustomMetadata customMetadata, bool immediateStart)
        {
            var uploadOptionsSWIG = uploadOptions.ToSWIG();

            _uploadOptions.Add(uploadOptionsSWIG);

            using (SWIG.UplinkUploadResult uploadResult = await Task.Run(() => SWIG.storj_uplink.uplink_upload_object(_access._project, bucket.Name, targetPath, uploadOptionsSWIG)).ConfigureAwait(false))
            {
                UploadOperation upload = new UploadOperation(stream, uploadResult, targetPath, customMetadata);
                if (immediateStart)
                {
                    upload.StartUploadAsync(); //Don't await it, otherwise it would "block" UploadObjectAsync
                }
                return(upload);
            }
        }
Пример #20
0
        async void UploadProgress(UploadOperation upload)
        {
            LogStatus(string.Format("Progress: {0}, Status: {1}", upload.Guid, upload.Progress.Status));

            BackgroundUploadProgress progress = upload.Progress;

            double percentSent = 100;

            if (progress.TotalBytesToSend > 0)
            {
                var bs = progress.BytesSent;
                percentSent = bs * 100 / progress.TotalBytesToSend;
            }

            SendNotify(percentSent);
            //MarshalLog(String.Format(" - Sent bytes: {0} of {1} ({2}%)",
            //  progress.BytesSent, progress.TotalBytesToSend, percentSent));

            LogStatus(string.Format(" - Sent bytes: {0} of {1} ({2}%), Received bytes: {3} of {4}",
                                    progress.BytesSent, progress.TotalBytesToSend, percentSent,
                                    progress.BytesReceived, progress.TotalBytesToReceive));

            if (progress.HasRestarted)
            {
                LogStatus(" - Upload restarted");
            }

            if (progress.HasResponseChanged)
            {
                var resp = upload.GetResponseInformation();
                // We've received new response headers from the server.
                LogStatus(" - Response updated; Header count: " + resp.Headers.Count);
                var          response = upload.GetResultStreamAt(0);
                StreamReader stream   = new StreamReader(response.AsStreamForRead());
                Debug.WriteLine("----------------------------------------Response from upload----------------------------------");
                var st = stream.ReadToEnd();
                Debug.WriteLine(st);
                //var res = JsonConvert.DeserializeObject<APIResponseOverride>(st);
                //await ConfigureMediaPhotoAsync(res.upload_id, Caption, null, null);
                await FinishVoiceAsync();

                //UploadCompleted?.Invoke(null, Convert.ToInt64(res.upload_id));
                // If you want to stream the response data this is a good time to start.
                // upload.GetResultStreamAt(0);
            }
        }
Пример #21
0
        /// <summary>
        /// 处理并监视指定的后台上传任务
        /// </summary>
        /// <param name="upload">后台上传任务</param>
        /// <param name="isNew">是否是新增的任务</param>
        private async Task HandleUploadAsync(UploadOperation upload, bool isNew)
        {
            try
            {
                // 将 UploadOperation 附加到 TransferModel,以便上传进度可通知
                TransferModel transfer = new TransferModel();
                transfer.UploadOperation = upload;
                transfer.Source          = "多个文件";
                transfer.Destination     = upload.RequestedUri.ToString();
                transfer.Progress        = upload.Progress.Status.ToString() + "0 / 0";

                _transfers.Add(transfer);

                WriteLine("Task Count: " + _transfers.Count.ToString());

                // 当上传进度发生变化时的回调函数
                Progress <UploadOperation> progressCallback = new Progress <UploadOperation>(UploadProgress);

                if (isNew)
                {
                    await upload.StartAsync().AsTask(_cancelToken.Token, progressCallback); // 启动一个后台上传任务
                }
                else
                {
                    await upload.AttachAsync().AsTask(_cancelToken.Token, progressCallback); // 监视已存在的后台上传任务
                }
                // 上传完成后获取服务端的响应信息
                ResponseInformation response = upload.GetResponseInformation();
                WriteLine("Completed: " + response.ActualUri + ", HttpStatusCode: " + response.StatusCode.ToString());
            }
            catch (TaskCanceledException) // 调用 CancellationTokenSource.Cancel() 后会抛出此异常
            {
                WriteLine("Canceled: " + upload.Guid);
            }
            catch (Exception ex)
            {
                // 将异常转换为 WebErrorStatus 枚举,如果获取到的是 WebErrorStatus.Unknown 则说明此次异常不是涉及 web 的异常
                WebErrorStatus error = BackgroundTransferError.GetStatus(ex.HResult);

                WriteLine(ex.ToString());
            }
            finally
            {
                _transfers.Remove(_transfers.First(p => p.UploadOperation == upload));
            }
        }
Пример #22
0
        /// <summary>
        /// Start uplaod and create handler.
        /// </summary>
        /// <param name="upload">UploadOperation handled.</param>
        /// <param name="start">Whether uplaod is started.</param>
        /// <returns>
        /// Represent the asynchronous operation.
        /// </returns>
        private async Task HandleUploadAsync(UploadOperation upload, bool start)
        {
            try
            {
                try
                {
                    Progress <UploadOperation> progressCallback = new Progress <UploadOperation>(UploadProgress);
                    if (start)
                    {
                        // Start the upload and attach a progress handler.
                        await upload.StartAsync().AsTask(cts.Token, progressCallback);
                    }
                    else
                    {
                        // The upload was already running when the application started, re-attach the progress handler.
                        await upload.AttachAsync().AsTask(cts.Token, progressCallback);
                    }
                }
                catch
                {
                    ShowMessageDialog("Error90! Upload canceled.");
                }

                ResponseInformation response = upload.GetResponseInformation();
                foreach (var c in response.Headers)
                {
                    System.Diagnostics.Debug.WriteLine("{0}, {1}. markkkkkkkk", c.Key, c.Value);
                }

                if (images != null && images.Count != 0 && hasImage == false)
                {
                    toBeUploadCourse.ImageUri = response.Headers[images.FirstOrDefault().Name];
                    hasImage = true;
                }
                SaveUploadLessonToListAsync(response);
            }
            catch (TaskCanceledException)
            {
                ShowMessageDialog("Error9! Upload canceled.");
            }
            catch
            {
                ShowMessageDialog("Error10! Upload canceled.");
                //throw;
            }
        }
Пример #23
0
        private async void FinishUpload(UploadOperation operation, ICompletedUpload upload)
        {
            if (operation.Progress.Status == BackgroundTransferStatus.Completed)
            {
                try
                {
                    string serverResponse = await(new StreamReader(
                                                      operation.GetResultStreamAt(0).AsStreamForRead())).ReadToEndAsync();

                    var newUpload = new CompletedUpload
                    {
                        Id             = upload.Id,
                        Name           = upload.Name,
                        ContentType    = upload.ContentType,
                        ServerResponse = serverResponse
                    };

                    await _database.InsertOrReplaceAsync(newUpload);

                    var result = await _uploadsPostprocessor.ProcessUploadAsync(newUpload);

                    if (result != UploadsPostprocessorResultType.ConnectionError)
                    {
                        await _database.RemoveAsync(operation.Guid);
                    }
                }
                catch (Exception ex)
                {
                    _logService.LogException(ex);
                }
            }
            else
            {
                await _database.RemoveAsync(operation.Guid);
            }

            OnUploadProgressChanged(operation, upload);

            _cts.Remove(operation.Guid);
            _uploads.Remove(operation);

            if (_uploads.Count == 0)
            {
                UploadsCompleted?.Invoke(this, EventArgs.Empty);
            }
        }
Пример #24
0
        private async Task HandleUploadAsync(UploadOperation upload, bool start)
        {
            var progressCallback = new Progress <UploadOperation>(UploadProgress);

            if (start)
            {
                // Start the upload and attach a progress handler.
                await upload.StartAsync().AsTask(_cts.Token, progressCallback);
            }
            else
            {
                // The upload was already running when the application started, re-attach the progress handler.
                await upload.AttachAsync().AsTask(_cts.Token, progressCallback);
            }

            var response = upload.GetResponseInformation();
        }
Пример #25
0
 private async void UploadOperation_UploadOperationEnded(UploadOperation uploadOperation)
 {
     UploadOperation.UploadOperationProgressChanged -= UploadOperation_UploadOperationProgressChanged;
     UploadOperation.UploadOperationEnded           -= UploadOperation_UploadOperationEnded;
     if (uploadOperation.Completed)
     {
         BucketContentViewModel.ActiveUploadOperations[_bucketContentViewModel.BucketName].Remove(uploadOperation);
         await _bucketContentViewModel.RefreshAsync();
     }
     else
     {
         RaiseChanged(nameof(UploadOperation));
         RaiseChanged(nameof(UploadPercentage));
         RaiseChanged(nameof(UploadFailed));
         RaiseChanged(nameof(UploadRunning));
     }
 }
        /// <summary>
        /// This is the progress changed event which will return progress.
        /// </summary>
        /// <param name="upload"></param>
        private static void UploadProgress(UploadOperation upload)
        {
            BackgroundUploadProgress progress = upload.Progress;

            double percentSent = 100;

            if (progress.TotalBytesToSend > 0)
            {
                percentSent = progress.BytesSent * 100 / progress.TotalBytesToSend;
                if (OnUploadProgressChanged != null)
                {
                    OnUploadProgressChanged(percentSent, (double)progress.BytesSent, (double)progress.TotalBytesToSend);
                }
            }
            //pbProgress.Value = percentSent;
            //tblockPercentageDownloaded.Text = percentSent + "%";
        }
        public UploadHttpTask(TaskConfiguration config, UploadOperation operation, bool restart) : base(config, true)
        {
            this.operation     = operation;
            this.Identifier    = operation.Guid.ToString();
            this.LocalFilePath = operation.SourceFile.ToString();

            var task = restart ? this.operation.AttachAsync() : this.operation.StartAsync();

            task.AsTask(
                CancellationToken.None,
                new Progress <UploadOperation>(x => this.SetData(
                                                   x.Progress.Status,
                                                   x.Progress.BytesSent,
                                                   x.Progress.TotalBytesToSend,
                                                   x.Progress.HasRestarted
                                                   )
                                               ));
        }
Пример #28
0
        private async void StartUpload_Click(object sender, RoutedEventArgs e)
        {
            // By default 'serverAddressField' is disabled and URI validation is not required. When enabling the text
            // box validating the URI is required since it was received from an untrusted source (user input).
            // The URI is validated by calling Uri.TryCreate() that will return 'false' for strings that are not valid URIs.
            // Note that when enabling the text box users may provide URIs to machines on the intrAnet that require
            // the "Home or Work Networking" capability.
            Uri uri;

            if (!Uri.TryCreate(serverAddressField.Text.Trim(), UriKind.Absolute, out uri))
            {
                rootPage.NotifyUser("Invalid URI.", NotifyType.ErrorMessage);
                return;
            }

            // Verify that we are currently not snapped, or that we can unsnap to open the picker.
            if (ApplicationView.Value == ApplicationViewState.Snapped && !ApplicationView.TryUnsnap())
            {
                rootPage.NotifyUser("File picker cannot be opened in snapped mode. Please unsnap first.", NotifyType.ErrorMessage);
                return;
            }

            FileOpenPicker picker = new FileOpenPicker();

            picker.FileTypeFilter.Add("*");
            StorageFile file = await picker.PickSingleFileAsync();

            if (file == null)
            {
                rootPage.NotifyUser("No file selected.", NotifyType.ErrorMessage);
                return;
            }

            BackgroundUploader uploader = new BackgroundUploader();

            uploader.SetRequestHeader("Filename", file.Name);

            UploadOperation upload = uploader.CreateUpload(uri, file);

            Log(String.Format("Uploading {0} to {1}, {2}", file.Name, uri.AbsoluteUri, upload.Guid));

            // Attach progress and completion handlers.
            await HandleUploadAsync(upload, true);
        }
Пример #29
0
        // Note that this event is invoked on a background thread, so we cannot access the UI directly.
        private void UploadProgress(UploadOperation upload)
        {
            var progress = upload.Progress;

            double percentSent = 100;

            if (progress.TotalBytesToSend > 0)
            {
                percentSent = progress.BytesSent * 100 / progress.TotalBytesToSend;
            }

            _currentProgressBar.Value = percentSent;

            if (progress.HasResponseChanged)
            {
                // If you want to stream the response data this is a good time to start.
                // upload.GetResultStreamAt(0);
            }
        }
Пример #30
0
        async Task <ResponseInfo> GetUploadResponse(UploadOperation operation)
        {
            await Task.Delay(1000);

            ResponseInfo ret = new ResponseInfo();
            await operation.StartAsync();

            IInputStream stream = operation.GetResultStreamAt(0);
            StreamReader sr     = new StreamReader(stream.AsStreamForRead());

            ret.Response = await sr.ReadToEndAsync();

            var info = operation.GetResponseInformation();

            ret.StatusCode = info.StatusCode;
            ret.Headers    = info.Headers;
            ret.RequestUri = info.ActualUri;
            return(ret);
        }
Пример #31
0
        static void Main(string[] args)
        {
            string login = string.Empty;
            string pass = string.Empty;
            string host = string.Empty;
            var correctParameters = args.Length == 1;
            if (correctParameters)
            {
                try
                {
                    var connectString = args[0];
                    var passDelimiter = connectString.IndexOf(":");
                    var hostDelimiter = connectString.IndexOf("@");

                    login = connectString.Substring(0, passDelimiter);
                    pass = connectString.Substring(passDelimiter + 1, hostDelimiter - passDelimiter - 1);
                    host = connectString.Substring(hostDelimiter + 1, connectString.Length - hostDelimiter - 1);
                    correctParameters = !string.IsNullOrWhiteSpace(login) && !string.IsNullOrWhiteSpace(pass) && !string.IsNullOrWhiteSpace(host);
                }
                catch
                {
                    correctParameters = false;
                }
            }

            if (!correctParameters)
            {
                Console.WriteLine("Incorrect parameter. Usage: ftpClient <login>:<password>@<host>");
                return;
            }

            Console.WriteLine($"Connecting to: {host} using LOGIN: {login} & PASSWORD: {pass}");

            var mode = TransferMode.Active;
            var controlChannel = new ControlChannel();
            if (!controlChannel.Init(host, login, pass))
            {
                return;
            }

            OperationBase currentOperation = null;
            string cmd = null;
            do
            {
                Console.Write("ftpClient> ");
                var cmdLine = Console.ReadLine();
                var cmdParams = cmdLine.Split(' ');
                cmd = cmdParams.Length > 0 ? cmdParams[0].ToLower() : string.Empty;

                currentOperation = null;

                switch (cmd)
                {
                    case "ls":
                    case "dir":
                        {
                            currentOperation = new DirectoryListingOperation(cmdParams.Length > 1 ? cmdParams[1] : null);
                            break;
                        }
                    case "recv":
                    case "get":
                        {
                            if (cmdParams.Length < 2 || cmdParams.Length > 3)
                            {
                                Console.WriteLine($"Incorrect command usage! Type: {cmdParams[0].ToUpper()} remote_file_name [local_file_name]");
                                continue;
                            }
                            currentOperation =
                                new DownloadOperation(
                                    new DirectoryInfo(Environment.CurrentDirectory),
                                    cmdParams[1],
                                    cmdParams.Length > 2 ? cmdParams[2] : null);
                            break;
                        }
                    case "send":
                    case "put":
                        {
                            if (cmdParams.Length < 2 || cmdParams.Length > 3)
                            {
                                Console.WriteLine($"Incorrect command usage! Type: {cmdParams[0].ToUpper()} local_file_name [remote_file_name]");
                                continue;
                            }
                            currentOperation =
                                new UploadOperation(
                                    new DirectoryInfo(Environment.CurrentDirectory),
                                    cmdParams[1],
                                    cmdParams.Length > 2 ? cmdParams[2] : null);
                            break;
                        }
                    case "delete":
                        {
                            if (cmdParams.Length != 2)
                            {
                                Console.WriteLine($"Incorrect command usage! Type: DELETE remote_file_name");
                                continue;
                            }
                            string response;
                            controlChannel.SendCommand($"DELE {cmdParams[1]}", out response);
                            break;
                        }
                    case "mode":
                        {
                            if (cmdParams.Length != 2 || (cmdParams[1].ToLower() != "a" && cmdParams[1].ToLower() != "p"))
                            {
                                Console.WriteLine("Incorrect command usage! Type: MODE [a|p]");
                                continue;
                            }

                            mode = cmdParams[1].ToLower() == "a" ? TransferMode.Active : TransferMode.Passive;
                            Console.WriteLine($"{mode.ToString().ToUpper()} data transfer mode set.");
                            break;
                        }
                    case "mkdir":
                        {
                            if (cmdParams.Length != 2)
                            {
                                Console.WriteLine("Incorrect command usage! Type: MKDIR directory_name");
                                continue;
                            }

                            string response;
                            controlChannel.SendCommand($"MKD {cmdParams[1]}", out response);
                            break;
                        }
                    case "rmdir":
                        {
                            if (cmdParams.Length != 2)
                            {
                                Console.WriteLine("Incorrect command usage! Type: RMDIR directory_name");
                                continue;
                            }

                            string response;
                            controlChannel.SendCommand($"RMD {cmdParams[1]}", out response);
                            break;
                        }
                    case "cd":
                        {
                            if (cmdParams.Length != 2)
                            {
                                Console.WriteLine("Incorrect command usage! Type: CD directory_name");
                                continue;
                            }

                            string response;
                            controlChannel.SendCommand($"CWD {cmdParams[1]}", out response);
                            break;
                        }
                    case "cdup":
                        {
                            string response;
                            controlChannel.SendCommand($"CDUP", out response);
                            break;
                        }
                    case "site":
                        {
                            if (cmdParams.Length > 2)
                            {
                                Console.WriteLine($"Incorrect command usage! Type: SITE [site_specific_command]");
                                continue;
                            }

                            string response;
                            controlChannel.SendCommand($"SITE {(cmdParams.Length > 1 ? cmdParams[1] : string.Empty)}", out response);
                            currentOperation = null;
                            break;
                        }
                    case "quit":
                        {
                            string response;
                            controlChannel.SendCommand("QUIT", out response);
                            currentOperation = null;
                            break;
                        }
                    case "help":
                        {
                            Console.WriteLine("List of supported commands:");
                            Console.WriteLine("DIR(LS) [directory_name] - list content of the specified directory.");
                            Console.WriteLine("RECV(GET) <server_file_name> [local_file_name] - download file from the server.");
                            Console.WriteLine("SEND(PUT) <local_file_name> [server_file_name] - upload file to the server.");
                            Console.WriteLine("DELETE <server_file_name> - delete file on the server.");
                            Console.WriteLine("MODE <a|p> - set active or passive mode for the data channel.");
                            Console.WriteLine("MKDIR <directory_name> - create directory on the server.");
                            Console.WriteLine("RMDIR <directory_name> - remove directory on the server.");
                            Console.WriteLine("CD <directory_name> - change current server directory.");
                            Console.WriteLine("CDUP - change current server directory one level up.");
                            Console.WriteLine("SITE [custom_parameter] - site specific command.");
                            Console.WriteLine("QUIT - close ftpClient");
                            break;
                        }
                    default:
                        {
                            Console.WriteLine("Unknown command! Type HELP for the list of supported commands.");
                            break;
                        }
                }

                if (currentOperation != null && currentOperation.Init(controlChannel, mode))
                {
                    try
                    {
                        currentOperation.Process(controlChannel).Wait();
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }
                    finally
                    {
                        currentOperation.Finish();
                    }
                }

            } while (cmd != "quit" && controlChannel.IsConnected);

            controlChannel.Close();
        }