Inheritance: IBackgroundUploader, IBackgroundTransferBase
コード例 #1
0
        private static async Task<UploadOperation> CreateUploadOperationForCreateVideo(
            IStorageFile file, string token, BackgroundUploader uploader)
        {
            const string boundary = "videoboundary";

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

            BackgroundTransferContentPart metadataPart = new BackgroundTransferContentPart("token");

            metadataPart.SetText(token);
            //metadataPart.SetText("iamatoken");
            parts.Add(metadataPart);

            BackgroundTransferContentPart videoPart = new BackgroundTransferContentPart("content_file", file.Name);
            videoPart.SetFile(file);
            videoPart.SetHeader("Content-Type", file.ContentType);
            parts.Add(videoPart);

            return
                await uploader.CreateUploadAsync(
                    new Uri(AddVideoPostUri),
                    parts,
                    "form-data",
                    boundary);
        }
コード例 #2
0
        private static async Task<UploadOperation> CreateUploadOperationForCreateImage(
            IStorageFile file, string token, BackgroundUploader uploader)
        {
            const string boundary = "imgboundary";

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

            BackgroundTransferContentPart metadataPart = new BackgroundTransferContentPart("token");

            metadataPart.SetText(token);
            //metadataPart.SetText("iamatoken");
            parts.Add(metadataPart);

            BackgroundTransferContentPart imagePart = new BackgroundTransferContentPart("photo", file.Name);
            imagePart.SetFile(file);
            imagePart.SetHeader("Content-Type", file.ContentType);
            parts.Add(imagePart);

            return
                await uploader.CreateUploadAsync(
                    new Uri(HttpFotosSapoPtUploadpostHtmlUri),
                    parts,
                    "form-data",
                    boundary);
        }
コード例 #3
0
       // private const string bucketurl = "http://s3.amazonaws.com/";

       // private const string bucketurl = "com.mf.carl-prototype.s3.amazonaws.com";
        #region Upload
        public async Task UploadFile(IReadOnlyList<StorageFile> files)
        {
            try
            {
               

                basicAwsCredentials = new BasicAWSCredentials(accesskey, secretkey);
                List<BackgroundTransferContentPart> parts = new List<BackgroundTransferContentPart>();
                for (int i = 0; i < files.Count; i++)
                {
                    BackgroundTransferContentPart part = new BackgroundTransferContentPart(files[i].Name, files[i].Name);
                    this.Filename = files[i].Name;
                    part.SetFile(files[i]);
                    parts.Add(part);
                }
                //Uri uri = new Uri(bucketurl + ExistingBucketName + "/");
                //Uri uri = new Uri("https://com.mf.carl-prototype.s3-us-west-2.amazonaws.com/");
                Uri uri = new Uri("https://s3.amazonaws.com/" + ExistingBucketName +"/");
              //  Uri uri = new Uri("https://"+ExistingBucketName+".s3-us-west-2.amazonaws.com/" );
            
                BackgroundUploader uploader = new BackgroundUploader();

                PasswordCredential pwdCredential = new PasswordCredential();
                pwdCredential.UserName = accesskey;
                pwdCredential.Password = secretkey;
                uploader.ServerCredential = pwdCredential;
               // uploader.Method = "POST";
       
               // uploader.SetRequestHeader("Content-Type", "multipart/form-data;boundary=34");
                  uploader.ServerCredential = new PasswordCredential{ UserName=accesskey, Password= secretkey};
                UploadOperation upload = await uploader.CreateUploadAsync(uri, parts);
                // Attach progress and completion handlers.
                await HandleUploadAsync(upload, true);
            }
            catch(Exception ex)
            {

            }
        }
コード例 #4
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);
        }
コード例 #5
0
        private async void UploadSingleFile(Uri uri, StorageFile file)
        {
            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);
        }
コード例 #6
0
ファイル: S2_Upload.xaml.cs プロジェクト: mbin/Win81App
        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;
            }

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

            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);
        }
コード例 #7
0
ファイル: S2_Upload.xaml.cs プロジェクト: mbin/Win81App
        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);
        }
コード例 #8
0
        public async Task<CreateImageResult> CreateImageAsync(IStorageFile file, Image img)
        {
            ImageCreateResult res = null;
            try
            {
                using (EnsureCredentialsUseContext context = new EnsureCredentialsUseContext(
                    this.Username, this.Password, this.Accesskey, _client.InnerChannel))
                {
                    res = await this._client.ImageCreateAsync(img, FotosSapoPtInterface);
                }
            }
            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;
                }
            }
            if (res != null && res.result.ok)
            {
                BackgroundUploader uploader = new BackgroundUploader();

                //Default HTTP Method is POST (http://msdn.microsoft.com/en-us/library/windows/apps/xaml/windows.networking.backgroundtransfer.backgrounduploader.method.aspx)
                //uploader.Method = "POST";

                UploadOperation uploadOperation = 
                    await PhotosServiceClient.CreateUploadOperationForCreateImage(file, res.token, uploader);

                await uploadOperation.StartAsync();

                ResponseInformation responseInformation = uploadOperation.GetResponseInformation();

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

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

                /*
                 
                 * Bug!! Root element ("Upload") as diferent cases in error and in success responses
                 
                 * Must ask SAPO Photos Team about the latency at User creation
                 
                 * How can an application post photos for a user not being that user? Seems to be possible.
                 
                 * Return usefull information 
                 
                 */

                string resultCode =
                    xDocument
                        .Descendants("uploadPost")
                        .Select(e => e.Element("Result").Value)
                        .SingleOrDefault();
                return new CreateImageResult(res.image, resultCode);
            }
            throw new Exception("Request cannot be fulfilled");
        }
        private async void OnGetUploadLinkCompleted(LiveOperationResult result)
        {
            if (result.Error != null)
            {
                this.taskCompletionSource.SetException(result.Error);
                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 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;

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

            this.taskCompletionSource.SetResult(new LiveUploadOperation(uploadOperation));
        }
コード例 #10
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 = 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);
        }
コード例 #11
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);
        }
コード例 #12
0
ファイル: Uploading.xaml.cs プロジェクト: CloudEDU/Courstore
        /// <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.");
            }
        }
コード例 #13
0
ファイル: Uploading.xaml.cs プロジェクト: CloudEDU/Courstore
        /// <summary>
        /// Invoked when upload button in popup is clicked and add new lesson.
        /// </summary>
        /// <param name="sender">The upload button clicked.</param>
        /// <param name="e">Event data that describes how the click was initiated.</param>
        private async void UploadLessionButton_Click(object sender, RoutedEventArgs e)
        {
            if (!CheckLessonInfomation())
            {
                ShowMessageDialog("Format error1! Please check your upload infomation.");
                return;
            }
            lessonUploadProgressRing.IsActive = true;
            UploadLessionButton.Visibility = Visibility.Collapsed;
            CancelUploadButton.Visibility = Visibility.Collapsed;
            allLessons.Add(new Lesson(++lessonCount, lessonName.Text, lessonDescription.Text));

            List<BackgroundTransferContentPart> docParts = CreateBackgroundTransferContentPartList(docs);
            List<BackgroundTransferContentPart> audioParts = CreateBackgroundTransferContentPartList(audios);
            List<BackgroundTransferContentPart> videoParts = CreateBackgroundTransferContentPartList(videos);

            List<BackgroundTransferContentPart> allParts = new List<BackgroundTransferContentPart>();
            if (docParts != null) allParts.AddRange(docParts);
            if (audioParts != null) allParts.AddRange(audioParts);
            if (videoParts != null) allParts.AddRange(videoParts);

            Uri uploadUri = new Uri(Constants.DataCenterURI + "Upload.aspx?username="******"Network connection error2!");
                lessonCount--;
                ResetPopup();
                return;
            }

            AddLessonInfo();
            lessonScrollView.ScrollToVerticalOffset(lessonScrollView.VerticalOffset);
            lessonUploadProgressRing.IsActive = false;
            UploadLessionButton.Visibility = Visibility.Visible;
            CancelUploadButton.Visibility = Visibility.Visible;
            wholeFrame.Opacity = 1;
            addLessonPopup.IsOpen = false;
        }
コード例 #14
0
        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);
        }
コード例 #15
0
        private async void Button_Click_1(object sender, RoutedEventArgs e)
        {
            FileOpenPicker openPicker = new FileOpenPicker
            {
                ViewMode = PickerViewMode.Thumbnail,
                SuggestedStartLocation = PickerLocationId.PicturesLibrary
            };
            openPicker.FileTypeFilter.Add(".jpg");
            openPicker.FileTypeFilter.Add(".jpeg");
            openPicker.FileTypeFilter.Add(".png");
            StorageFile file = await openPicker.PickSingleFileAsync();
            if (file != null)
            {
                const string authorizationEndpoint =
                    "https://login.live.com/oauth20_authorize.srf";//Put the Authorization endpoint here

                const string tokenEndpoint = "https://login.live.com/oauth20_token.srf";//Put the Token endpoint here

                const string redirectUri = "";//Put the redirect uri that you registered for your client (App)

                const string responseType = "code";//for the authorization code flow this is the expected response_type

                const string scope = "wl.skydrive_update";//List of permissions that your client (App) intents to have

                const string state = "";//Client provided value that the Authorization Server MUST return if provided (for security purposes)

                const string clientId = "";//Put your client id here

                const string clientSecret = "";//Put your client secret here

                TokenEndpointResponse tokenEndpointResponse =
                    await OAuthHelper.GetAuthorization(authorizationEndpoint, tokenEndpoint, redirectUri,
                        responseType, scope, state, clientId, clientSecret);

                if (tokenEndpointResponse == null)
                {
                    this.tblock_danceResult.Text = "Error or user refused to authorize";
                    return;
                }

                BackgroundUploader uploader = new BackgroundUploader();

                uploader.Method = "PUT";
                uploader.SetRequestHeader("Authorization", 
                    tokenEndpointResponse.TokenType + " " + tokenEndpointResponse.AccessToken);

                Uri protectedResourceUri = new Uri("https://apis.live.net/v5.0/me/skydrive/files/" + file.Name);

                UploadOperation uploadOperation = uploader.CreateUpload(protectedResourceUri, file);

                await uploadOperation.StartAsync();

                this.tblock_danceResult.Text = "SUCCESS";

            }
            else
            {
                //picker dismissed
            }


            //HttpClient client = new HttpClient();

            //client.DefaultRequestHeaders.Authorization =
            //    new AuthenticationHeaderValue(tokenEndpointResponse.TokenType, tokenEndpointResponse.AccessToken);

            //string protectedResourceUri = "https://apis.live.net/v5.0/me/skydrive/files/";

            //HttpResponseMessage getUserDetailsResponse =
            //    await
            //        client.GetAsync(new Uri(protectedResourceUri));

            //string getUserDetailsResponseBody = await getUserDetailsResponse.Content.ReadAsStringAsync();

            //this.tblock_danceResult.Text = getUserDetailsResponseBody;
        }