Наследование: IUploadOperation, IBackgroundTransferOperation
Пример #1
0
        private async static Task<string> GetResponseMessage(UploadOperation uploadOperation)
        {
            ResponseInformation responseInformation = uploadOperation.GetResponseInformation();

            //uint contentLength = Convert.ToUInt32(responseInformation.Headers["Content-Length"]);

            uint contentLength = (uint)uploadOperation.Progress.BytesReceived;

            uint statusCode = responseInformation.StatusCode;

            IInputStream resultStreamAt = uploadOperation.GetResultStreamAt(0);

            IBuffer result = await resultStreamAt.ReadAsync(
                new Windows.Storage.Streams.Buffer(contentLength),
                contentLength,
                InputStreamOptions.None);

            Stream responseStream = result.AsStream();

            XDocument xDocument = XDocument.Load(responseStream);

            foreach (XElement xe in xDocument.Root.Descendants())
            {
                if (xe.Name.LocalName.Equals("Ok"))
                {
                    return "SUCCESS";
                }
                if (xe.Name.LocalName.Equals("Error"))
                {
                    return xe.Value;
                }
            }
            return "Unspecified error submiting video";
        }
Пример #2
0
        private async Task UploadProgress(UploadOperation obj)
        {
            Debug.WriteLine(obj.Progress.BytesSent * 100 / obj.Progress.TotalBytesToSend);

            if (obj.Progress.HasResponseChanged)
            {
                var stream = obj.GetResultStreamAt(0);
                var reader = new StreamReader(stream.AsStreamForRead());
                var results = await reader.ReadToEndAsync();

                var image = JsonConvert.DeserializeObject<ImageResponse>(results);
                //<?xml version="1.0" encoding="utf-8"?><rsp stat="ok"><method>smugmug.images.upload</method><Image id="2125852928" Key="R6bnfnM" URL="http://photos.jenkinsfamily.com.au/Other/Nat/25253579_mbht3D#2125852928_R6bnfnM"/></rsp>

            }
        }
        /// <summary>
        /// Called when a progress event is raised from the BT.UploadOperation and this
        /// will call this TailoredUploadOperation's progress handler.
        /// </summary>
        private void OnUploadProgress(BT.UploadOperation uploadOp)
        {
            Debug.Assert(uploadOp != null);

            if (uploadOp.Progress.Status == BT.BackgroundTransferStatus.Error ||
                uploadOp.Progress.Status == BT.BackgroundTransferStatus.Canceled ||
                this.isAttach ||
                this.Progress == null)
            {
                return;
            }

            this.Progress.Report(
                new LiveOperationProgress(
                    (long)uploadOp.Progress.BytesSent,
                    (long)uploadOp.Progress.TotalBytesToSend));
        }
        public async void Attach(BT.UploadOperation uploadOp)
        {
            Debug.Assert(uploadOp != null);

            this.uploadOp    = uploadOp;
            this.isAttach    = true;
            this.uploadOpCts = new CancellationTokenSource();
            var progressHandler = new Progress <BT.UploadOperation>(this.OnUploadProgress);

            try
            {
                // Since we don't provide API for apps to attach to pending upload operations, we have no
                // way to invoke the app event handler to provide any feedback. We would just ignore the result here.
                this.uploadOp = await this.uploadOp.AttachAsync().AsTask(this.uploadOpCts.Token, progressHandler);
            }
            catch
            {
                // Ignore errors as well.
            }
        }
        private bool IsExceptionHandled(string title, Exception ex, UploadOperation upload = null)
        {
            WebErrorStatus error = BackgroundTransferError.GetStatus(ex.HResult);
            if (error == WebErrorStatus.Unknown)
            {
                return false;
            }

            if (upload == null)
            {
                LogStatus(String.Format(CultureInfo.CurrentCulture, "Error: {0}: {1}", title, error), 
                    NotifyType.ErrorMessage);
            }
            else
            {
                LogStatus(String.Format(CultureInfo.CurrentCulture, "Error: {0} - {1}: {2}", upload.Guid, title, 
                    error), NotifyType.ErrorMessage);
            }

            return true;
        }
        private async Task HandleUploadAsync(UploadOperation upload, bool start)
        {
            try
            {
                LogStatus("Running: " + upload.Guid, NotifyType.StatusMessage);

                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);
                }

                ResponseInformation response = upload.GetResponseInformation();

                LogStatus(String.Format(CultureInfo.CurrentCulture, "Completed: {0}, Status Code: {1}", upload.Guid,
                    response.StatusCode), NotifyType.StatusMessage);
            }
            catch (TaskCanceledException)
            {
                LogStatus("Canceled: " + upload.Guid, NotifyType.StatusMessage);
            }
            catch (Exception ex)
            {
                if (!IsExceptionHandled("Error", ex, upload))
                {
                    throw;
                }
            }
        }
        // Note that this event is invoked on a background thread, so we cannot access the UI directly.
        private void UploadProgress(UploadOperation upload)
        {
            MarshalLog(String.Format(CultureInfo.CurrentCulture, "Progress: {0}, Status: {1}", upload.Guid, 
                upload.Progress.Status));

            BackgroundUploadProgress progress = upload.Progress;

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

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

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

            if (progress.HasResponseChanged)
            {
                // We've received new response headers from the server.
                MarshalLog(" - Response updated; Header count: " + upload.GetResponseInformation().Headers.Count);

                // If you want to stream the response data this is a good time to start.
                // upload.GetResultStreamAt(0);
            }
        }
        private async Task HandleUploadAsync(UploadOperation upload, bool start)
        {
            try
            {
                CancellationTokenSource cts = new CancellationTokenSource();
                Progress<UploadOperation> progressCallback = new Progress<UploadOperation>();
                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);
                }

                ResponseInformation response = upload.GetResponseInformation();
                //  Log(String.Format("Completed: {0}, Status Code: {1}", upload.Guid, response.StatusCode));
            }
            catch (TaskCanceledException)
            {
                // Log("Upload cancelled.");
            }
            catch (Exception ex)
            {
                //LogException("Error", ex);
            }
        }
 /// <summary>
 /// Initializes a new instance of LiveUplaodOperation class.
 /// </summary>
 /// <param name="uploadOperaton"></param>
 internal LiveUploadOperation(UploadOperation uploadOperation)
 {
     this.uploadOperation = uploadOperation;
 }
        private async void OnGetUploadLinkCompleted(LiveOperationResult result)
        {
            if (this.Status == OperationStatus.Cancelled)
            {
                base.OnCancel();
                return;
            }

            if (result.Error != null || result.IsCancelled)
            {
                this.OnOperationCompleted(result);
                return;
            }

            var uploadUrl = new Uri(result.RawResult, UriKind.Absolute);

            // NOTE: the GetUploadLinkOperation will return a uri with the overwite, suppress_response_codes,
            // and suppress_redirect query parameters set.
            Debug.Assert(uploadUrl.Query != null);
            Debug.Assert(uploadUrl.Query.Contains(QueryParameters.Overwrite));
            Debug.Assert(uploadUrl.Query.Contains(QueryParameters.SuppressRedirects));
            Debug.Assert(uploadUrl.Query.Contains(QueryParameters.SuppressResponseCodes));

            var uploader = new BT.BackgroundUploader();
            uploader.Group = LiveConnectClient.LiveSDKUploadGroup;
            if (this.LiveClient.Session != null)
            {
                uploader.SetRequestHeader(
                    ApiOperation.AuthorizationHeader,
                    AuthConstants.BearerTokenType + " " + this.LiveClient.Session.AccessToken);
            }
            uploader.SetRequestHeader(ApiOperation.LibraryHeader, Platform.GetLibraryHeaderValue());
            uploader.Method = HttpMethods.Put;

            this.uploadOpCts = new CancellationTokenSource();
            Exception webError = null;

            LiveOperationResult opResult = null;
            try
            {
                if (this.InputStream != null)
                {
                    this.uploadOp = await uploader.CreateUploadFromStreamAsync(uploadUrl, this.InputStream);
                }
                else
                {
                    this.uploadOp = uploader.CreateUpload(uploadUrl, this.InputFile);
                }

                var progressHandler = new Progress<BT.UploadOperation>(this.OnUploadProgress);

                this.uploadOp = await this.uploadOp.StartAsync().AsTask(this.uploadOpCts.Token, progressHandler);
            }
            catch (TaskCanceledException exception)
            {
                opResult = new LiveOperationResult(exception, true);
            }
            catch (Exception exp)
            {
                // This might be an server error. We will read the response to determine the error message.
                webError = exp;
            }

            if (opResult == null)
            {
                try
                {
                    IInputStream responseStream = this.uploadOp.GetResultStreamAt(0);
                    if (responseStream == null)
                    {
                        var error = new LiveConnectException(
                            ApiOperation.ApiClientErrorCode,
                            ResourceHelper.GetString("ConnectionError"));
                        opResult = new LiveOperationResult(error, false);
                    }
                    else
                    {
                        var reader = new DataReader(responseStream);
                        uint length = await reader.LoadAsync(MaxUploadResponseLength);
                        opResult = ApiOperation.CreateOperationResultFrom(reader.ReadString(length), ApiMethod.Upload);

                        if (webError != null && opResult.Error != null && !(opResult.Error is LiveConnectException))
                        {
                            // If the error did not come from the api service,
                            // we'll just return the error thrown by the uploader.
                            opResult = new LiveOperationResult(webError, false);
                        }
                    }
                }
                catch (COMException exp)
                {
                    opResult = new LiveOperationResult(exp, false);
                }
                catch (FileNotFoundException exp)
                {
                    opResult = new LiveOperationResult(exp, false);
                }
            }

            this.OnOperationCompleted(opResult);
        }
        public async void Attach(BT.UploadOperation uploadOp)
        {
            Debug.Assert(uploadOp != null);

            this.uploadOp = uploadOp;
            this.isAttach = true;
            this.uploadOpCts = new CancellationTokenSource();
            var progressHandler = new Progress<BT.UploadOperation>(this.OnUploadProgress);

            try
            {
                // Since we don't provide API for apps to attach to pending upload operations, we have no
                // way to invoke the app event handler to provide any feedback. We would just ignore the result here.
                this.uploadOp = await this.uploadOp.AttachAsync().AsTask(this.uploadOpCts.Token, progressHandler);
            }
            catch
            {
                // Ignore errors as well. 
            }
        }
        // Note that this event is invoked on a background thread, so we cannot access the UI directly.
        private void UploadProgress(UploadOperation upload)
        {
            // UploadOperation.Progress is updated in real-time while the operation is ongoing. Therefore,
            // we must make a local copy at the beginning of the progress handler, so that we can have a consistent
            // view of that ever-changing state throughout the handler's lifetime.
            BackgroundUploadProgress currentProgress = upload.Progress;

            MarshalLog(String.Format(CultureInfo.CurrentCulture, "Progress: {0}, Status: {1}", upload.Guid, 
                currentProgress.Status));

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

            MarshalLog(String.Format(CultureInfo.CurrentCulture, 
                " - Sent bytes: {0} of {1} ({2}%), Received bytes: {3} of {4}", currentProgress.BytesSent, 
                currentProgress.TotalBytesToSend, percentSent, currentProgress.BytesReceived, currentProgress.TotalBytesToReceive));

            if (currentProgress.HasRestarted)
            {
                MarshalLog(" - Upload restarted");
            }

            if (currentProgress.HasResponseChanged)
            {
                // We've received new response headers from the server.
                MarshalLog(" - Response updated; Header count: " + upload.GetResponseInformation().Headers.Count);

                // If you want to stream the response data this is a good time to start.
                // upload.GetResultStreamAt(0);
            }
        }
        private async void OnGetUploadLinkCompleted(LiveOperationResult result)
        {
            if (this.Status == OperationStatus.Cancelled)
            {
                base.OnCancel();
                return;
            }

            if (result.Error != null || result.IsCancelled)
            {
                this.OnOperationCompleted(result);
                return;
            }

            var uploadUrl = new Uri(result.RawResult, UriKind.Absolute);

            // NOTE: the GetUploadLinkOperation will return a uri with the overwite, suppress_response_codes,
            // and suppress_redirect query parameters set.
            Debug.Assert(uploadUrl.Query != null);
            Debug.Assert(uploadUrl.Query.Contains(QueryParameters.Overwrite));
            Debug.Assert(uploadUrl.Query.Contains(QueryParameters.SuppressRedirects));
            Debug.Assert(uploadUrl.Query.Contains(QueryParameters.SuppressResponseCodes));

            var uploader = new BT.BackgroundUploader();

            uploader.Group = LiveConnectClient.LiveSDKUploadGroup;
            if (this.LiveClient.Session != null)
            {
                uploader.SetRequestHeader(
                    ApiOperation.AuthorizationHeader,
                    AuthConstants.BearerTokenType + " " + this.LiveClient.Session.AccessToken);
            }
            uploader.SetRequestHeader(ApiOperation.LibraryHeader, Platform.GetLibraryHeaderValue());
            uploader.Method = HttpMethods.Put;

            this.uploadOpCts = new CancellationTokenSource();
            Exception webError = null;

            LiveOperationResult opResult = null;

            try
            {
                if (this.InputStream != null)
                {
                    this.uploadOp = await uploader.CreateUploadFromStreamAsync(uploadUrl, this.InputStream);
                }
                else
                {
                    this.uploadOp = uploader.CreateUpload(uploadUrl, this.InputFile);
                }

                var progressHandler = new Progress <BT.UploadOperation>(this.OnUploadProgress);

                this.uploadOp = await this.uploadOp.StartAsync().AsTask(this.uploadOpCts.Token, progressHandler);
            }
            catch (TaskCanceledException exception)
            {
                opResult = new LiveOperationResult(exception, true);
            }
            catch (Exception exp)
            {
                // This might be an server error. We will read the response to determine the error message.
                webError = exp;
            }

            if (opResult == null)
            {
                try
                {
                    IInputStream responseStream = this.uploadOp.GetResultStreamAt(0);
                    if (responseStream == null)
                    {
                        var error = new LiveConnectException(
                            ApiOperation.ApiClientErrorCode,
                            ResourceHelper.GetString("ConnectionError"));
                        opResult = new LiveOperationResult(error, false);
                    }
                    else
                    {
                        var  reader = new DataReader(responseStream);
                        uint length = await reader.LoadAsync(MaxUploadResponseLength);

                        opResult = this.CreateOperationResultFrom(reader.ReadString(length));

                        if (webError != null && opResult.Error != null && !(opResult.Error is LiveConnectException))
                        {
                            // If the error did not come from the api service,
                            // we'll just return the error thrown by the uploader.
                            opResult = new LiveOperationResult(webError, false);
                        }
                    }
                }
                catch (COMException exp)
                {
                    opResult = new LiveOperationResult(exp, false);
                }
                catch (FileNotFoundException exp)
                {
                    opResult = new LiveOperationResult(exp, false);
                }
            }

            this.OnOperationCompleted(opResult);
        }
Пример #14
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;
            }
        }
Пример #15
0
        /// <summary>
        /// Event is invoked on a background thread.
        /// </summary>
        /// <param name="upload">UploadOperation.</param>
        private void UploadProgress(UploadOperation upload)
        {
            // Progress: upload.Guid; Statues: uplaod.Progress.Status

            BackgroundUploadProgress progress = upload.Progress;

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

            // Send bytes: progress.BytesSend of progress.TotalBytesSend (percentSend%)
            // Received bytes: progress.BytesReceived of progress.TotalBytesToReceive

            if (progress.HasRestarted)
            {
                // Upload restarted
                System.Diagnostics.Debug.WriteLine("Upload restarted");
            }

            if (progress.HasResponseChanged)
            {
                // Response updated; Header count: upload.GetResponseInformation().Headers.Count
            }
        }