public static async Task<string> UploadImageAsync(Stream imageStream)
        {
            CloudStorageAccount account = new CloudStorageAccount(
            useHttps: true,
            storageCredentials: new Microsoft.WindowsAzure.Storage.Auth.StorageCredentials(
                    accountName: Constants.StorageAccountName,
                    keyValue: Constants.StorageAccessKey)
                    );

            try
            {
                var blobClient = account.CreateCloudBlobClient();
                var container = blobClient.GetContainerReference("visitors");
                var blob = container.GetBlockBlobReference(Guid.NewGuid().ToString() + ".jpg");
                using (var stream = imageStream.AsInputStream())
                {
                    await blob.UploadFromStreamAsync(stream);
                }
                return blob.Uri.ToString();
            }
            catch (Exception ex)
            {
                return null;
            }
        }
Пример #2
0
        public async static Task<byte[]> getBytes(Stream stream)
        {
            IInputStream inputStream = stream.AsInputStream();
            DataReader dataReader = new DataReader(inputStream);

            await dataReader.LoadAsync((uint)stream.Length);
            byte[] buffer = new byte[(int)stream.Length];

            dataReader.ReadBytes(buffer);

            return buffer;
        }
Пример #3
0
 /// <summary>
 /// Write the contents of stream to filename in the cache location. If a null stream is provided, the file is created with no contents.
 /// </summary>
 /// <param name="stream">Content to be written to file</param>
 /// <param name="filename">Name of the file to be written in cache location</param>
 private static async Task WriteFileAsync(Stream stream, string filename)
 {
     // Prepare output file stream
     StorageFolder parent = GetCacheFolder();
     StorageFile file = null;
     try
     {
         file = await parent.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
     }
     catch (Exception)
     {
     }
     if (file != null && stream != null)
     {
         // Prepare input image stream
         IInputStream inStream = stream.AsInputStream();
         DataReader reader = new DataReader(inStream);
         IRandomAccessStream fileStream = null;
         try
         {
             fileStream = await file.OpenAsync(FileAccessMode.ReadWrite);
             // Buffered write to file
             await reader.LoadAsync(1024);
             while (reader.UnconsumedBufferLength > 0)
             {
                 await fileStream.WriteAsync(reader.ReadBuffer(reader.UnconsumedBufferLength));
                 await reader.LoadAsync(1024);
             }
         }
         catch (Exception)
         {
         }
         finally
         {
             if (fileStream != null)
             {
                 fileStream.FlushAsync();
             }
         }
         inStream.Dispose();
     }
 }
Пример #4
0
		protected override async void init(Stream stream, bool flip, Loader.LoadedCallbackMethod loadedCallback)
		{
			try
			{
				using (var memoryStream = new InMemoryRandomAccessStream())
				{
					await RandomAccessStream.CopyAsync(stream.AsInputStream(), memoryStream);

					var decoder = await BitmapDecoder.CreateAsync(memoryStream);
					var frame = await decoder.GetFrameAsync(0);

					var transform = new BitmapTransform();
					transform.InterpolationMode = BitmapInterpolationMode.NearestNeighbor;
					transform.Rotation = BitmapRotation.None;
					var dataProvider = await decoder.GetPixelDataAsync(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Straight, transform, ExifOrientationMode.IgnoreExifOrientation, ColorManagementMode.ColorManageToSRgb);
					var data = dataProvider.DetachPixelData();
			
					int width = (int)decoder.PixelWidth;
					int height = (int)decoder.PixelHeight;
					Mipmaps = new Mipmap[1];
					Size = new Size2(width, height);

					Mipmaps[0] = new Mipmap(data, width, height, 1, 4);
					if (flip) Mipmaps[0].FlipVertical();
				}
			}
			catch (Exception e)
			{
				FailedToLoad = true;
				Loader.AddLoadableException(e);
				if (loadedCallback != null) loadedCallback(this, false);
				return;
			}

			Loaded = true;
			if (loadedCallback != null) loadedCallback(this, true);
		}
Пример #5
0
        private async Task SendFileAsync(String url, StorageFile sFile, HttpMethod httpMethod)
        {
            //Log data for upload attempt
            Windows.Storage.FileProperties.BasicProperties fileProperties = await sFile.GetBasicPropertiesAsync();

            Dictionary <string, string> properties = new Dictionary <string, string> {
                { "File Size", fileProperties.Size.ToString() }
            };

            App.Controller.TelemetryClient.TrackEvent("OneDrive picture upload attempt", properties);
            HttpStreamContent streamContent = null;

            try
            {
                //Open file to send as stream
                Stream stream = await sFile.OpenStreamForReadAsync();

                streamContent = new HttpStreamContent(stream.AsInputStream());
                Debug.WriteLine("SendFileAsync() - sending: " + sFile.Path);
            }
            catch (FileNotFoundException ex)
            {
                Debug.WriteLine(ex.Message);

                // Log telemetry event about this exception
                var events = new Dictionary <string, string> {
                    { "OneDrive", ex.Message }
                };
                App.Controller.TelemetryClient.TrackEvent("FailedToOpenFile", events);
            }
            catch (Exception ex)
            {
                // Log telemetry event about this exception
                var events = new Dictionary <string, string> {
                    { "OneDrive", ex.Message }
                };
                App.Controller.TelemetryClient.TrackEvent("FailedToOpenFile", events);

                throw new Exception("SendFileAsync() - Cannot open file. Err= " + ex.Message);
            }

            if (streamContent == null)
            {
                //Throw exception if stream is not created
                Debug.WriteLine("  File Path = " + (sFile != null ? sFile.Path : "?"));
                throw new Exception("SendFileAsync() - Cannot open file.");
            }

            try
            {
                Uri resourceAddress = new Uri(url);
                //Create requst to upload file
                using (HttpRequestMessage request = new HttpRequestMessage(httpMethod, resourceAddress))
                {
                    request.Content = streamContent;

                    // Do an asynchronous POST.
                    using (HttpResponseMessage response = await httpClient.SendRequestAsync(request).AsTask(cts.Token))
                    {
                        await DebugTextResultAsync(response);

                        if (response.StatusCode != HttpStatusCode.Created)
                        {
                            throw new Exception("SendFileAsync() - " + response.StatusCode);
                        }
                    }
                }
            }
            catch (TaskCanceledException ex)
            {
                // Log telemetry event about this exception
                var events = new Dictionary <string, string> {
                    { "OneDrive", ex.Message }
                };
                App.Controller.TelemetryClient.TrackEvent("CancelledFileUpload", events);

                throw new Exception("SendFileAsync() - " + ex.Message);
            }
            catch (Exception ex)
            {
                // This failure will already be logged in telemetry in the enclosing UploadPictures function. We don't want this to be recorded twice.

                throw new Exception("SendFileAsync() - Error: " + ex.Message);
            }
            finally
            {
                streamContent.Dispose();
                Debug.WriteLine("SendFileAsync() - final.");
            }

            App.Controller.TelemetryClient.TrackEvent("OneDrive picture upload success", properties);
        }
Пример #6
0
        private async void btn_Random_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                pr_Load.Visibility = Visibility.Visible;
                Uri uri = new Uri("ms-appx:///Assets/avatar/ic_avatar" + new Random().Next(1, 12) + ".jpg");
                RandomAccessStreamReference    streamRef = RandomAccessStreamReference.CreateFromUri(uri);
                Windows.Storage.Streams.Buffer buffer    = null;
                using (IRandomAccessStreamWithContentType fileStream = await streamRef.OpenReadAsync())
                {
                    buffer = new Windows.Storage.Streams.Buffer((uint)fileStream.Size);
                    await fileStream.ReadAsync(buffer, (uint)fileStream.Size, InputStreamOptions.None);
                }

                Stream stream  = WindowsRuntimeBufferExtensions.AsStream(buffer);
                string resutls = "";
                // resutls = await WebClientClass.PostResults(new Uri(string.Format("https://account.bilibili.com/pendant/updateFace?type=jpg&size=s")), stream.AsInputStream(), "https://account.bilibili.com/site/updateface.html?type=face");
                // resutls = await WebClientClass.PostResults(new Uri(string.Format("https://account.bilibili.com/pendant/updateFace?type=jpg&size=m")), stream.AsInputStream(), "https://account.bilibili.com/site/updateface.html?type=face");
                resutls = await WebClientClass.PostResults(new Uri(string.Format("https://account.bilibili.com/pendant/updateFace?type=jpg&size=l")), stream.AsInputStream(), "https://account.bilibili.com/site/updateface.html?type=face");

                JObject obj = JObject.Parse(resutls);
                if (obj["state"].ToString() == "OK")
                {
                    MessageCenter.SendLogined();
                    Utils.ShowMessageToast("头像更换成功", 3000);
                }
                else
                {
                    Utils.ShowMessageToast("头像更换失败", 3000);
                }
            }
            catch (Exception ex)
            {
                Utils.ShowMessageToast("头像更换失败\r\n" + ex.Message, 3000);
            }
            finally
            {
                pr_Load.Visibility = Visibility.Collapsed;
                GetProfile();
            }
        }
 // Summary:
 //     Upload files by output stream.
 //
 // Parameters:
 //  sourceFolderId:
 //      The id of the place you want to upload.
 //
 //  fileName:
 //      The name you want to use after upload.
 //
 // Returns:
 //     The StorageFolder where you downloaded folder.
 public async Task<bool> UploadFileStreamAsync(string folderIdToStore, string fileName, Stream outstream)
 {
     //ProgressBar progressBar = new ProgressBar();
     //progressBar.Value = 0;
     //var progressHandler = new Progress<LiveOperationProgress>(
     //    (progress) => { progressBar.Value = progress.ProgressPercentage; });
     System.Threading.CancellationTokenSource ctsUpload = new System.Threading.CancellationTokenSource();
     try
     {
         //LiveOperationResult result = await this.LiveClient
         //    .UploadAsync(folderIdToStore, fileName, outstream, OverwriteOption.Overwrite, ctsUpload.Token, progressHandler);
         LiveOperationResult result = await this.LiveClient.BackgroundUploadAsync(folderIdToStore, fileName, outstream.AsInputStream(), OverwriteOption.Overwrite);
     }
     catch
     {
         ctsUpload.Cancel();
         throw new ShareException(fileName, ShareException.ShareType.UPLOAD);
     }
     return true;
 }
#pragma warning disable 4014
        /// <summary>
        /// Starts an asynchronous PutBlock operation as soon as the parallel
        /// operation semaphore becomes available.
        /// </summary>
        /// <param name="blockData">Data to be uploaded</param>
        /// <param name="blockId">Block ID</param>
        /// <returns>A task that represents the asynchronous write operation.</returns>
        /// <remarks>Warning CS4014 is disabled here, since we intentionally do not
        /// await PutBlockAsync call.</remarks>
        private async Task WriteBlockAsync(Stream blockData, string blockId, string blockMD5)
        {
            Interlocked.Increment(ref this.pendingWrites);
            this.noPendingWritesEvent.Reset();

            await this.parallelOperationSemaphore.WaitAsync();

            // Without await have found last block doesn't get uploaded properly and noPendingWritesEvent will always equal 1.
            // Then the putblocklist will never happen, therefore no blob. Bug #211
            await this.blockBlob.PutBlockAsync(blockId, blockData.AsInputStream(), blockMD5, this.accessCondition, this.options, this.operationContext).AsTask().ContinueWith(task =>
                {
                    if (task.Exception != null)
                    {
                        this.lastException = task.Exception;
                    }

                    if (Interlocked.Decrement(ref this.pendingWrites) == 0)
                    {
                        this.noPendingWritesEvent.Set();
                    }

                    this.parallelOperationSemaphore.Release();
                });
        }
Пример #9
0
 public JsonStreamCommandReader(Stream stream)
 {
     _dataReader = new DataReader(stream.AsInputStream());
 }
Пример #10
0
        /// <summary>
        /// Starts an asynchronous AppendBlock operation as soon as the parallel
        /// operation semaphore becomes available. Since parallelism is always set
        /// to 1 for append blobs, appendblock operations are called serially.
        /// </summary>
        /// <param name="blockData">Data to be uploaded</param>
        /// <param name="offset">Offset within the append blob to be used to set the append offset conditional header.</param>        
        /// <param name="blockMD5">MD5 hash of the data to be uploaded</param>
        /// <returns>A task that represents the asynchronous write operation.</returns>
        private async Task WriteAppendBlockAsync(Stream blockData, long offset, string blockMD5)
        {
            this.noPendingWritesEvent.Increment();
            await this.parallelOperationSemaphore.WaitAsync();

            this.accessCondition.IfAppendPositionEqual = offset;

            int previousResultsCount = this.operationContext.RequestResults.Count;
            Task writeBlockTask = this.appendBlob.AppendBlockAsync(blockData.AsInputStream(), blockMD5, this.accessCondition, this.options, this.operationContext).AsTask().ContinueWith(task =>
            {
                if (task.Exception != null)
                {
                    if (this.options.AbsorbConditionalErrorsOnRetry.Value
                        && this.operationContext.LastResult.HttpStatusCode == (int)HttpStatusCode.PreconditionFailed)
                    {
                        StorageExtendedErrorInformation extendedInfo = this.operationContext.LastResult.ExtendedErrorInformation;
                        if (extendedInfo != null 
                            && (extendedInfo.ErrorCode == BlobErrorCodeStrings.InvalidAppendCondition || extendedInfo.ErrorCode == BlobErrorCodeStrings.InvalidMaxBlobSizeCondition)
                            && (this.operationContext.RequestResults.Count - previousResultsCount > 1))
                        {
                            // Pre-condition failure on a retry should be ignored in a single writer scenario since the request
                            // succeeded in the first attempt.
                            Logger.LogWarning(this.operationContext, SR.PreconditionFailureIgnored);
                        }
                        else
                        {
                            this.lastException = task.Exception;
                        }
                    }
                    else
                    {
                        this.lastException = task.Exception;
                    }
                }

                this.noPendingWritesEvent.Decrement();
                this.parallelOperationSemaphore.Release();
            });
        }
Пример #11
0
        /// <summary>
        /// Helper method used for saving the content of a response to a file.
        /// This allows unittests to easily generate real data to use as mock responses.
        /// </summary>
        /// <param name="endpoint">API endpoint we are calling.</param>
        /// <param name="directory">Directory to store our file.</param>
        /// <param name="httpMethod">The http method to be performed.</param>
        /// <param name="requestBody">An optional stream to use for the request body content.</param>
        /// <param name="requestBodyContentType">The content type of the request stream.</param>
        /// <returns>Task waiting for HTTP call to return and file copy to complete.</returns>
        public async Task SaveEndpointResponseToFile(
            string endpoint,
            string directory,
            HttpMethods httpMethod,
            Stream requestBody            = null,
            string requestBodyContentType = null)
        {
            Uri uri = new Uri(this.deviceConnection.Connection, endpoint);

            // Convert the OS version, such as 14385.1002.amd64fre.rs1_xbox_rel_1608.160709-1700, into a friendly OS version, such as rs1_xbox_rel_1608
            string friendlyOSVersion = this.OperatingSystemVersion;

            string[] versionParts = friendlyOSVersion.Split('.');
            if (versionParts.Length == ExpectedOSVersionSections)
            {
                friendlyOSVersion = versionParts[TargetOSVersionSection];
            }

            // Create the filename as DeviceFamily_OSVersion.dat, replacing '/', '.', and '-' with '_' so
            // we can create a class with the same name as this Device/OS pair for tests.
            string filename = endpoint + "_" + this.Platform.ToString() + "_" + friendlyOSVersion;

            if (httpMethod != HttpMethods.Get)
            {
                filename = httpMethod.ToString() + "_" + filename;
            }

            Utilities.ModifyEndpointForFilename(ref filename);

            filename += ".dat";
            string filepath = Path.Combine(directory, filename);

            if (HttpMethods.WebSocket == httpMethod)
            {
#if WINDOWS_UWP
                WebSocket <object> websocket = new WebSocket <object>(this.deviceConnection, true);
#else
                WebSocket <object> websocket = new WebSocket <object>(this.deviceConnection, this.ServerCertificateValidation, true);
#endif // WINDOWS_UWP

                ManualResetEvent streamReceived = new ManualResetEvent(false);
                Stream           stream         = null;

                WindowsDevicePortal.WebSocketStreamReceivedEventInternalHandler <object> streamReceivedHandler =
                    delegate(WebSocket <object> sender, WebSocketMessageReceivedEventArgs <Stream> args)
                {
                    if (args.Message != null)
                    {
                        stream = args.Message;
                        streamReceived.Set();
                    }
                };

                websocket.WebSocketStreamReceived += streamReceivedHandler;

                Task startListeningForStreamTask = websocket.StartListeningForMessages(endpoint);
                startListeningForStreamTask.Wait();

                streamReceived.WaitOne();

                Task stopListeningForStreamTask = websocket.StopListeningForMessages();
                stopListeningForStreamTask.Wait();

                websocket.WebSocketStreamReceived -= streamReceivedHandler;

                using (stream)
                {
                    using (var fileStream = File.Create(filepath))
                    {
                        stream.Seek(0, SeekOrigin.Begin);
                        stream.CopyTo(fileStream);
                    }
                }
            }
            else if (HttpMethods.Put == httpMethod)
            {
#if WINDOWS_UWP
                HttpStreamContent streamContent = null;
#else
                StreamContent streamContent = null;
#endif // WINDOWS_UWP

                if (requestBody != null)
                {
#if WINDOWS_UWP
                    streamContent = new HttpStreamContent(requestBody.AsInputStream());
                    streamContent.Headers.ContentType = new HttpMediaTypeHeaderValue(requestBodyContentType);
#else
                    streamContent = new StreamContent(requestBody);
                    streamContent.Headers.ContentType = new MediaTypeHeaderValue(requestBodyContentType);
#endif // WINDOWS_UWP
                }

                using (Stream dataStream = await this.Put(uri, streamContent))
                {
                    using (var fileStream = File.Create(filepath))
                    {
                        dataStream.Seek(0, SeekOrigin.Begin);
                        dataStream.CopyTo(fileStream);
                    }
                }
            }
            else if (HttpMethods.Post == httpMethod)
            {
                using (Stream dataStream = await this.Post(uri, requestBody, requestBodyContentType))
                {
                    using (var fileStream = File.Create(filepath))
                    {
                        dataStream.Seek(0, SeekOrigin.Begin);
                        dataStream.CopyTo(fileStream);
                    }
                }
            }
            else if (HttpMethods.Delete == httpMethod)
            {
                using (Stream dataStream = await this.Delete(uri))
                {
                    using (var fileStream = File.Create(filepath))
                    {
                        dataStream.Seek(0, SeekOrigin.Begin);
                        dataStream.CopyTo(fileStream);
                    }
                }
            }
            else if (HttpMethods.Get == httpMethod)
            {
                using (Stream dataStream = await this.Get(uri))
                {
                    using (var fileStream = File.Create(filepath))
                    {
                        dataStream.Seek(0, SeekOrigin.Begin);
                        dataStream.CopyTo(fileStream);
                    }
                }
            }
            else
            {
                throw new NotImplementedException(string.Format("Unsupported HttpMethod {0}", httpMethod.ToString()));
            }
        }
Пример #12
0
        private async Task SetContactProperties(StoredContact contact, User user, User originalUser = null)
        {
            if (contact != null)
            {
                contact.RemoteId   = (ContactsManager.GetRemoteId(user));
                contact.GivenName  = (user.first_name);
                contact.FamilyName = (user.last_name);
                if (!string.IsNullOrWhiteSpace(user.photo_max) && !user.photo_max.EndsWith(".gif"))
                {
                    Stream stream = await HttpExtensions.TryGetResponseStreamAsync(user.photo_max);

                    if (stream == null)
                    {
                        throw new Exception("failed to download contact pic " + user.photo_max);
                    }
                    await contact.SetDisplayPictureAsync(stream.AsInputStream());
                }
                IDictionary <string, object> dictionary = await contact.GetPropertiesAsync();

                if (!string.IsNullOrWhiteSpace(user.site))
                {
                    dictionary[KnownContactProperties.Url] = user.site;
                }
                if (!string.IsNullOrWhiteSpace(user.mobile_phone) && this.IsPhoneNumber(user.mobile_phone))
                {
                    List <string> var_6_262 = BaseFormatterHelper.ParsePhoneNumbers(user.mobile_phone);
                    if (var_6_262.Count >= 1)
                    {
                        dictionary[KnownContactProperties.MobileTelephone] = var_6_262[0];
                    }
                    if (var_6_262.Count >= 2)
                    {
                        dictionary[KnownContactProperties.AlternateMobileTelephone] = var_6_262[1];
                    }
                }
                if (!string.IsNullOrWhiteSpace(user.home_phone) && this.IsPhoneNumber(user.home_phone))
                {
                    List <string> var_7_2D8 = BaseFormatterHelper.ParsePhoneNumbers(user.home_phone);
                    if (var_7_2D8.Count >= 1)
                    {
                        dictionary[KnownContactProperties.Telephone] = var_7_2D8[0];
                    }
                    if (var_7_2D8.Count >= 2)
                    {
                        dictionary[KnownContactProperties.AlternateTelephone] = var_7_2D8[1];
                    }
                }
                DateTime var_8;
                if (!string.IsNullOrWhiteSpace(user.bdate) && ContactsManager.TryParseDateTimeFromString(user.bdate, out var_8))
                {
                    var_8 = var_8.Add(DateTime.Now - DateTime.UtcNow);
                    new DateTimeOffset(var_8.Year, var_8.Month, var_8.Day, 0, 0, 0, 0, TimeSpan.Zero);
                    dictionary[KnownContactProperties.Birthdate] = new DateTimeOffset(var_8);
                }
            }
            if (originalUser != null)
            {
                originalUser.first_name   = user.first_name;
                originalUser.last_name    = user.last_name;
                originalUser.site         = user.site;
                originalUser.mobile_phone = user.mobile_phone;
                originalUser.home_phone   = user.home_phone;
                originalUser.photo_max    = user.photo_max;
                originalUser.bdate        = user.bdate;
            }
        }
Пример #13
0
        private async Task <IInputStream> OpenReadAsync(string key)
        {
            Stream stream = await m_objectStore.OpenReadStreamAsync(key);

            return(stream.AsInputStream());
        }
Пример #14
0
 /// <summary>
 /// Loads the data from an image stream and returns a new WriteableBitmap.
 /// </summary>
 /// <param name="stream">The stream with the image data.</param>
 /// <param name="pixelFormat">The pixel format of the stream data. If Unknown is provided as param, the default format of the BitmapDecoder is used.</param>
 /// <returns>A new WriteableBitmap containing the pixel data.</returns>
 public static async Task<WriteableBitmap> FromStream(Stream stream, BitmapPixelFormat pixelFormat = BitmapPixelFormat.Unknown)
 {
     using (var dstStream = new InMemoryRandomAccessStream())
     {
         await RandomAccessStream.CopyAsync(stream.AsInputStream(), dstStream);
         return await FromStream(dstStream);
     }
 }
Пример #15
0
        protected override async Task <string> RequestAsync(string address, String requestData = null, Stream imageData = null)
        {
            try
            {
                if (requestData != null)
                {
                    address += "?" + requestData;
                }

                UtilityHelper.CountlyLogging("POST " + address);

                //make sure stream is at start
                imageData?.Seek(0, SeekOrigin.Begin);

                var httpResponseMessage = await Client.PostAsync(new Uri(address), (imageData != null)?new HttpStreamContent(imageData.AsInputStream()) : null);

                if (httpResponseMessage.IsSuccessStatusCode)
                {
                    return(await httpResponseMessage.Content.ReadAsStringAsync());
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception ex)
            {
                UtilityHelper.CountlyLogging("Encountered a exception while making a POST request, " + ex.ToString());
                return(null);
            }
        }
Пример #16
0
 public IInputStream GetInputStreamAt(ulong position)
 {
     internstream.Position = (long)position;
     return(internstream.AsInputStream());
 }
Пример #17
0
#pragma warning disable CS0618
#pragma warning disable CS1998
        public static async Task <bool> ImportAnchors(this WindowsMRAnchorSubsystem wmrrp, Stream input)
        {
            bool ret = false;

#if ENABLE_WINMD_SUPPORT
            try
            {
                var access = await SpatialAnchorTransferManager.RequestAccessAsync();

                if (access != SpatialPerceptionAccessStatus.Allowed)
                {
                    return(ret);
                }

                var spatialAnchorStore = await SpatialAnchorManager.RequestStoreAsync();

                if (spatialAnchorStore == null)
                {
                    return(ret);
                }

                var anchors = await SpatialAnchorTransferManager.TryImportAnchorsAsync(input.AsInputStream());

                foreach (var kvp in anchors)
                {
                    spatialAnchorStore.TrySave(kvp.Key, kvp.Value);
                }

                ret = true;
            }
            catch (Exception e)
            {
                Debug.Log(e);
                ret = false;
            }
#else
            Debug.LogError("This API is only available for use in UWP based applications.");
#endif //ENABLE_WINMD_SUPPORT
            return(ret);
        }
Пример #18
0
        private static async Task <string> RequestAsync(string address, Stream data = null)
        {
            try
            {
                if (Countly.IsLoggingEnabled)
                {
                    Debug.WriteLine("POST " + address);
                }

                var httpResponseMessage = await Client.PostAsync(new Uri(address), (data != null)?new HttpStreamContent(data.AsInputStream()) : null);

                if (httpResponseMessage.IsSuccessStatusCode)
                {
                    return(await httpResponseMessage.Content.ReadAsStringAsync());
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception ex)
            {
                if (Countly.IsLoggingEnabled)
                {
                    //Debug.WriteLine("Encountered a exception while making a POST request");
                    //Debug.WriteLine(ex);
                }
                return(null);
            }
        }
Пример #19
0
        private async void LoadStrokesFromStream(Stream stream)
        {
            await inkManager.LoadAsync(stream.AsInputStream());

            needToRedrawInkSurface = true;
        }
Пример #20
0
 public XBeeStreamWrapper(Stream stream)
 {
     _stream       = stream;
     _outputStream = _stream.AsOutputStream();
     _inputStream  = _stream.AsInputStream();
 }
        public static async void Upload(string uri, Stream data, string paramName, string uploadContentType,Action<VKHttpResult> resultCallback, Action<double> progressCallback = null, string fileName = null)
        {
#if SILVERLIGHT
            var rState = new RequestState();
            rState.resultCallback = resultCallback;
#endif
            try
            {
#if SILVERLIGHT
                var request = (HttpWebRequest)WebRequest.Create(uri);
            
                request.AllowWriteStreamBuffering = false;
                rState.request = request;
                request.Method = "POST";
                string formDataBoundary = String.Format("----------{0:N}", Guid.NewGuid());
                string contentType = "multipart/form-data; boundary=" + formDataBoundary;
                request.ContentType = contentType;
                request.CookieContainer = new CookieContainer();

                string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\";\r\nContent-Type: {3}\r\n\r\n",
                               formDataBoundary,
                               paramName,
                               fileName ?? "myDataFile",
                               uploadContentType);

                string footer = "\r\n--" + formDataBoundary + "--\r\n";

                request.ContentLength = Encoding.UTF8.GetByteCount(header) + data.Length + Encoding.UTF8.GetByteCount(footer);

                request.BeginGetRequestStream(ar =>
                {
                    try
                    {
                        var requestStream = request.EndGetRequestStream(ar);

                        requestStream.Write(Encoding.UTF8.GetBytes(header), 0, Encoding.UTF8.GetByteCount(header));

                        StreamUtils.CopyStream(data, requestStream, progressCallback);

                        requestStream.Write(Encoding.UTF8.GetBytes(footer), 0, Encoding.UTF8.GetByteCount(footer));

                        requestStream.Close();

                        request.BeginGetResponse(new AsyncCallback(ResponseCallback), rState);
                    }
                    catch (Exception ex)
                    {
                        Logger.Error("VKHttpRequestHelper.Upload failed to write data to request stream.", ex);
                        SafeClose(rState);
                        SafeInvokeCallback(rState.resultCallback, false, null);
                    }

                }, null);
#else

                var httpClient = new Windows.Web.Http.HttpClient();
                HttpMultipartFormDataContent content = new HttpMultipartFormDataContent();
                content.Add(new HttpStreamContent(data.AsInputStream()), paramName, fileName ?? "myDataFile");
                content.Headers.Add("Content-Type", uploadContentType);
                var postAsyncOp =  httpClient.PostAsync(new Uri(uri, UriKind.Absolute),
                    content);

                postAsyncOp.Progress = (r, progress) =>
                    {
                        if (progressCallback != null && progress.TotalBytesToSend.HasValue && progress.TotalBytesToSend > 0)
                        {
                            progressCallback(((double)progress.BytesSent * 100) / progress.TotalBytesToSend.Value);
                        }
                    };


                var result = await postAsyncOp;

                var resultStr = await result.Content.ReadAsStringAsync();

                SafeInvokeCallback(resultCallback, result.IsSuccessStatusCode, resultStr);
#endif
            }
            catch (Exception exc)
            {
                Logger.Error("VKHttpRequestHelper.Upload failed.", exc);
#if SILVERLIGHT
                SafeClose(rState);
                   SafeInvokeCallback(rState.resultCallback, false, null);
#else
                SafeInvokeCallback(resultCallback, false, null);
#endif

            }
        }
 /// <summary>
 /// Loads the data from an image stream and fills this WriteableBitmap with it.
 /// </summary>
 /// <param name="bmp">The WriteableBitmap.</param>
 /// <param name="stream">The stream with the image data.</param>
 /// <returns>The WriteableBitmap that was passed as parameter.</returns>
 public static async Task<WriteableBitmap> FromStream(this WriteableBitmap bmp, Stream stream)
 {
    using (var dstStream = new InMemoryRandomAccessStream())
    {
       await RandomAccessStream.CopyAsync(stream.AsInputStream(), dstStream);
       return await FromStream(bmp, dstStream);
    }
 }
Пример #23
0
        public static async void Upload(string uri, Stream data, string paramName, string uploadContentType, Action <VKHttpResult> resultCallback, Action <double> progressCallback = null, string fileName = null)
        {
#if SILVERLIGHT
            var rState = new RequestState();
            rState.resultCallback = resultCallback;
#endif
            try
            {
#if SILVERLIGHT
                var request = (HttpWebRequest)WebRequest.Create(uri);

                request.AllowWriteStreamBuffering = false;
                rState.request = request;
                request.Method = "POST";
                string formDataBoundary = String.Format("----------{0:N}", Guid.NewGuid());
                string contentType      = "multipart/form-data; boundary=" + formDataBoundary;
                request.ContentType     = contentType;
                request.CookieContainer = new CookieContainer();

                string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\";\r\nContent-Type: {3}\r\n\r\n",
                                              formDataBoundary,
                                              paramName,
                                              fileName ?? "myDataFile",
                                              uploadContentType);

                string footer = "\r\n--" + formDataBoundary + "--\r\n";

                request.ContentLength = Encoding.UTF8.GetByteCount(header) + data.Length + Encoding.UTF8.GetByteCount(footer);

                request.BeginGetRequestStream(ar =>
                {
                    try
                    {
                        var requestStream = request.EndGetRequestStream(ar);

                        requestStream.Write(Encoding.UTF8.GetBytes(header), 0, Encoding.UTF8.GetByteCount(header));

                        StreamUtils.CopyStream(data, requestStream, progressCallback);

                        requestStream.Write(Encoding.UTF8.GetBytes(footer), 0, Encoding.UTF8.GetByteCount(footer));

                        requestStream.Close();

                        request.BeginGetResponse(new AsyncCallback(ResponseCallback), rState);
                    }
                    catch (Exception ex)
                    {
                        Logger.Error("VKHttpRequestHelper.Upload failed to write data to request stream.", ex);
                        SafeClose(rState);
                        SafeInvokeCallback(rState.resultCallback, false, null);
                    }
                }, null);
#else
                var httpClient = new Windows.Web.Http.HttpClient();
                HttpMultipartFormDataContent content = new HttpMultipartFormDataContent();
                content.Add(new HttpStreamContent(data.AsInputStream()), paramName, fileName ?? "myDataFile");
                content.Headers.Add("Content-Type", uploadContentType);
                var postAsyncOp = httpClient.PostAsync(new Uri(uri, UriKind.Absolute),
                                                       content);

                postAsyncOp.Progress = (r, progress) =>
                {
                    if (progressCallback != null && progress.TotalBytesToSend.HasValue && progress.TotalBytesToSend > 0)
                    {
                        progressCallback(((double)progress.BytesSent * 100) / progress.TotalBytesToSend.Value);
                    }
                };


                var result = await postAsyncOp;

                var resultStr = await result.Content.ReadAsStringAsync();

                SafeInvokeCallback(resultCallback, result.IsSuccessStatusCode, resultStr);
#endif
            }
            catch (Exception exc)
            {
                Logger.Error("VKHttpRequestHelper.Upload failed.", exc);
#if SILVERLIGHT
                SafeClose(rState);
                SafeInvokeCallback(rState.resultCallback, false, null);
#else
                SafeInvokeCallback(resultCallback, false, null);
#endif
            }
        }
Пример #24
0
        public async Task<AIResponse> VoiceRequestAsync(Stream voiceStream, RequestExtras requestExtras = null)
        {
            var request = new AIRequest
            {
                Language = config.Language.code,
                Timezone = TimeZoneInfo.Local.StandardName,
                SessionId = sessionId
            };

            if (requestExtras != null)
            {
                if (requestExtras.HasContexts)
                {
                    request.Contexts = requestExtras.Contexts;
                }

                if (requestExtras.HasEntities)
                {
                    request.Entities = requestExtras.Entities;
                }
            }

            try
            {
                var content = new HttpMultipartFormDataContent();
                
                var jsonRequest = JsonConvert.SerializeObject(request, Formatting.None, jsonSettings);

                if (config.DebugLog)
                {
                    Debug.WriteLine($"Request: {jsonRequest}");
                }

                content.Add(new HttpStringContent(jsonRequest, UnicodeEncoding.Utf8, "application/json"), "request");
                content.Add(new HttpStreamContent(voiceStream.AsInputStream()), "voiceData", "voice.wav");
                
                var response = await httpClient.PostAsync(new Uri(config.RequestUrl), content);
                return await ProcessResponse(response);
            }
            catch (Exception e)
            {
                throw new AIServiceException(e);
            }
        }
Пример #25
0
        public async void DoHttpClientRequest()
        {
            //根据是否存在body判断是Get请求还是Post请求
            RequestType method  = string.IsNullOrEmpty(_body) ? RequestType.Get : RequestType.Post;
            var         request = CreateHttp(_url, method);

            if (_httpClient != null)
            {
                try
                {
                    HttpResponseMessage response = null;
                    if (method == RequestType.Post)
                    {
                        //POST
                        //_httpProgressUpload = new Progress<HttpProcess>(ProgressUploadHandler);
                        //response = await _httpClient.SendRequestAsync(request).AsTask(_cts.Token, _progressUpload);
                        response = await _httpClient.SendRequestAsync(request).AsTask(_cts.Token);
                    }
                    else if (method == RequestType.Get)
                    {
                        //GET
                        //下载进度状态信息
                        _httpProgressDownload = new Progress <HttpProgress>(ProgressDownloadHandler);
                        try
                        {
                            response = await _httpClient.SendRequestAsync(request).AsTask(_cts.Token, _httpProgressDownload);

                            //HttpCompletionOption.ResponseHeadersRead多了这个参数    在接受到头之后完成。  于是就不继续进行了
                            //response = await _httpClient.SendRequestAsync(request, HttpCompletionOption.ResponseHeadersRead).AsTask(_cts.Token, _httpProgressDownload);

                            _cts.Token.ThrowIfCancellationRequested();

                            //处理流
                            using (Stream responseStream = (await response.Content.ReadAsInputStreamAsync()).AsStreamForRead())
                            {
                                //将Stream转换为IRandomAccessStream
                                var randomAccessStream = new InMemoryRandomAccessStream();
                                var outputStream       = randomAccessStream.GetOutputStreamAt(0);
                                await RandomAccessStream.CopyAsync(responseStream.AsInputStream(), outputStream);

                                if (randomAccessStream != null)
                                {
                                    if (SucceedEvent != null)
                                    {
                                        SucceedEvent(randomAccessStream);   //获取到源的回调方法,并返回获取的内容
                                    }
                                }
                            }
                        }
                        //中断Task时候会抛出异常,所以要通过try catch这种方法来获取是否终止。
                        catch (TaskCanceledException)
                        {
                            //请求被取消
                            CancelEvent("下载已停止");
                        }
                    }
                }
                catch (WebException e)
                {
                    FailedEvent(e.Message, e.Status);
                }
            }
        }
Пример #26
0
 public InputStreamWithDisposeCallback(Stream stream)
 {
     this.stream = stream.AsInputStream();
 }
Пример #27
0
        internal async static Task <StorageException> PopulateStorageExceptionFromHttpResponseMessage(HttpResponseMessage response, RequestResult currentResult)
        {
            if (!response.IsSuccessStatusCode)
            {
                try
                {
                    currentResult.HttpStatusMessage = response.ReasonPhrase;
                    currentResult.HttpStatusCode    = (int)response.StatusCode;
                    currentResult.ServiceRequestID  = HttpResponseMessageUtils.GetHeaderSingleValueOrDefault(response.Headers, Constants.HeaderConstants.RequestIdHeader);

                    string tempDate = HttpResponseMessageUtils.GetHeaderSingleValueOrDefault(response.Headers, Constants.HeaderConstants.Date);
                    currentResult.RequestDate = string.IsNullOrEmpty(tempDate) ? DateTime.Now.ToString("R", CultureInfo.InvariantCulture) : tempDate;

                    if (response.Headers.ETag != null)
                    {
                        currentResult.Etag = response.Headers.ETag.ToString();
                    }

                    if (response.Content != null && response.Content.Headers.ContentMD5 != null)
                    {
                        currentResult.ContentMd5 = Convert.ToBase64String(response.Content.Headers.ContentMD5);
                    }
                }
                catch (Exception)
                {
                    // no op
                }

                try
                {
                    Stream errStream = await response.Content.ReadAsStreamAsync();

                    currentResult.ExtendedErrorInformation = StorageExtendedErrorInformation.ReadFromStream(errStream.AsInputStream());
                }
                catch (Exception)
                {
                    // no op
                }

                return(new StorageException(currentResult, response.ReasonPhrase, null));
            }
            else
            {
                return(null);
            }
        }
Пример #28
0
        /// <summary>
        /// Return the MD5 hash of the provided memory stream as a string. Stream position will be equal to the length of stream on 
        /// return, this ensures the MD5 is consistent.
        /// </summary>
        /// <param name="streamToMD5">The bytes which will be checksummed</param>
        /// <returns>The MD5 checksum as a string</returns>
        public static string MD5(Stream streamToMD5)
        {
            if (streamToMD5 == null) throw new ArgumentNullException("streamToMD5", "Provided Stream cannot be null.");

            string resultStr;

#if NETFX_CORE
            var alg = Windows.Security.Cryptography.Core.HashAlgorithmProvider.OpenAlgorithm(Windows.Security.Cryptography.Core.HashAlgorithmNames.Md5);
            var buffer = (new Windows.Storage.Streams.DataReader(streamToMD5.AsInputStream())).ReadBuffer((uint)streamToMD5.Length);
            var hashedData = alg.HashData(buffer);
            resultStr = Windows.Security.Cryptography.CryptographicBuffer.EncodeToHexString(hashedData).Replace("-", "");
#else
            using (System.Security.Cryptography.HashAlgorithm md5 =
#if WINDOWS_PHONE
                new Tools.MD5Managed())
#else
 System.Security.Cryptography.MD5.Create())
#endif
            {
                //If we don't ensure the position is consistent the MD5 changes
                streamToMD5.Seek(0, SeekOrigin.Begin);
                resultStr = BitConverter.ToString(md5.ComputeHash(streamToMD5)).Replace("-", "");
            }
#endif
            return resultStr;
        }
Пример #29
0
        private async void btn_Select_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                pr_Load.Visibility = Visibility.Visible;
                Uri uri = new Uri("ms-appx:///Assets/avatar/ic_avatar" + new Random().Next(1, 12) + ".jpg");

                FileOpenPicker openPicker = new FileOpenPicker();
                openPicker.CommitButtonText       = "选中此文件";
                openPicker.ViewMode               = PickerViewMode.Thumbnail;
                openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
                openPicker.FileTypeFilter.Add(".jpg");
                openPicker.FileTypeFilter.Add(".gif");
                openPicker.FileTypeFilter.Add(".png");

                // 弹出文件选择窗口
                StorageFile file = await openPicker.PickSingleFileAsync(); // 用户在“文件选择窗口”中完成操作后,会返回对应的

                if (file == null)
                {
                    Utils.ShowMessageToast("没有选择图片", 3000);
                    return;
                }


                Stream stream = await file.OpenStreamForReadAsync();


                string resutls = "";
                // resutls = await WebClientClass.PostResults(new Uri(string.Format("https://account.bilibili.com/pendant/updateFace?type=jpg&size=s")), stream.AsInputStream(), "https://account.bilibili.com/site/updateface.html?type=face");
                // resutls = await WebClientClass.PostResults(new Uri(string.Format("https://account.bilibili.com/pendant/updateFace?type=jpg&size=m")), stream.AsInputStream(), "https://account.bilibili.com/site/updateface.html?type=face");
                resutls = await WebClientClass.PostResults(new Uri(string.Format("https://account.bilibili.com/pendant/updateFace?type=jpg&size=l")), stream.AsInputStream(), "https://account.bilibili.com/site/updateface.html?type=face");

                JObject obj = JObject.Parse(resutls);
                if (obj["state"].ToString() == "OK")
                {
                    MessageCenter.SendLogined();
                    Utils.ShowMessageToast("头像更换成功", 3000);
                }
                else
                {
                    Utils.ShowMessageToast("头像更换失败", 3000);
                }
            }
            catch (Exception ex)
            {
                Utils.ShowMessageToast("头像更换失败\r\n" + ex.Message, 3000);
            }
            finally
            {
                pr_Load.Visibility = Visibility.Collapsed;
                GetProfile();
            }
        }
Пример #30
0
        private async void LoadStrokesFromStream(Stream stream)
        {
            await inkManager.LoadAsync(stream.AsInputStream());

            strokeList.Clear();
            strokeList.AddRange(inkManager.GetStrokes());

            needsInkSurfaceValidation = true;
        }
Пример #31
0
        /// <summary>
        /// Submits the http post request to the specified uri.
        /// </summary>
        /// <param name="uri">The uri to which the post request will be issued.</param>
        /// <param name="requestStream">Optional stream containing data for the request body.</param>
        /// <param name="requestStreamContentType">The type of that request body data.</param>
        /// <param name="allowRetry">Allow the Post to be retried after issuing a Get call. Currently used for CSRF failures.</param>
        /// <returns>Task tracking the completion of the POST request</returns>
#pragma warning disable 1998
        private async Task <Stream> Post(
            Uri uri,
            Stream requestStream            = null,
            string requestStreamContentType = null,
            bool allowRetry = true)
        {
            HttpStreamContent requestContent = null;
            IBuffer           dataBuffer     = null;

            if (requestStream != null)
            {
                requestContent = new HttpStreamContent(requestStream.AsInputStream());
                requestContent.Headers.Remove(ContentTypeHeaderName);
                requestContent.Headers.TryAppendWithoutValidation(ContentTypeHeaderName, requestStreamContentType);
            }

            HttpBaseProtocolFilter httpFilter = new HttpBaseProtocolFilter();

            httpFilter.AllowUI = false;

            if (this.deviceConnection.Credentials != null)
            {
                httpFilter.ServerCredential          = new PasswordCredential();
                httpFilter.ServerCredential.UserName = this.deviceConnection.Credentials.UserName;
                httpFilter.ServerCredential.Password = this.deviceConnection.Credentials.Password;
            }

            using (HttpClient client = new HttpClient(httpFilter))
            {
                this.ApplyHttpHeaders(client, HttpMethods.Post);

                IAsyncOperationWithProgress <HttpResponseMessage, HttpProgress> responseOperation = client.PostAsync(uri, requestContent);
                TaskAwaiter <HttpResponseMessage> responseAwaiter = responseOperation.GetAwaiter();
                while (!responseAwaiter.IsCompleted)
                {
                }

                using (HttpResponseMessage response = responseOperation.GetResults())
                {
                    if (!response.IsSuccessStatusCode)
                    {
                        // If this isn't a retry and it failed due to a bad CSRF
                        // token, issue a GET to refresh the token and then retry.
                        if (allowRetry && this.IsBadCsrfToken(response))
                        {
                            await this.RefreshCsrfToken();

                            return(await this.Post(uri, requestStream, requestStreamContentType, false));
                        }

                        throw new DevicePortalException(response);
                    }

                    this.RetrieveCsrfToken(response);

                    if (response.Content != null)
                    {
                        using (IHttpContent messageContent = response.Content)
                        {
                            IAsyncOperationWithProgress <IBuffer, ulong> bufferOperation = messageContent.ReadAsBufferAsync();
                            while (bufferOperation.Status != AsyncStatus.Completed)
                            {
                            }

                            dataBuffer = bufferOperation.GetResults();
                        }
                    }
                }
            }

            return((dataBuffer != null) ? dataBuffer.AsStream() : null);
        }
Пример #32
0
        /*
         * 分为地图查找和交通路况显示,由checkbox控制
         */
        private async void searchMap(object sender, RoutedEventArgs e)
        {
            currentCity = "";
            if (searchTraffic.IsChecked == false)
            {
                if (mapSearchBlock.Text != "")
                {
                    string     url    = "http://restapi.amap.com/v3/geocode/geo?key=5fd3b8bd943a505ccfec387943bba945&address=" + mapSearchBlock.Text;
                    HttpClient client = new HttpClient();
                    string     result = await client.GetStringAsync(url);

                    JObject jo = (JObject)JsonConvert.DeserializeObject(result);
                    if (jo["status"].ToString() == "0" || jo["count"].ToString() == "0")
                    {
                        var i = new MessageDialog("查无此地区").ShowAsync();
                    }
                    else
                    {
                        JArray ja       = (JArray)jo["geocodes"];
                        string location = ja[0]["location"].ToString();
                        currentCity = ja[0]["formatted_address"].ToString();

                        string url2 = "http://restapi.amap.com/v3/staticmap?key=5fd3b8bd943a505ccfec387943bba945&location=" + location + "&zoom=10&size=731*458&labels=" + mapSearchBlock.Text + ",2,0,16,0xFFFFFF,0x008000:" + location;
                        HttpResponseMessage response = await client.GetAsync(url2);

                        BitmapImage bitmap = new BitmapImage();
                        Stream      stream = await response.Content.ReadAsStreamAsync();

                        IInputStream inputStream = stream.AsInputStream();
                        using (IRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream())
                        {
                            using (IOutputStream outputStream = randomAccessStream.GetOutputStreamAt(0))
                            {
                                await RandomAccessStream.CopyAsync(inputStream, outputStream);

                                randomAccessStream.Seek(0);
                                bitmap.SetSource(randomAccessStream);
                                map.Source = bitmap;
                            }
                        }
                    }
                }
            }
            else
            {
                if (mapSearchBlock.Text != "")
                {
                    string     url    = "http://restapi.amap.com/v3/geocode/geo?key=5fd3b8bd943a505ccfec387943bba945&address=" + mapSearchBlock.Text;
                    HttpClient client = new HttpClient();
                    string     result = await client.GetStringAsync(url);

                    JObject jo = (JObject)JsonConvert.DeserializeObject(result);
                    if (jo["status"].ToString() == "0" || jo["count"].ToString() == "0")
                    {
                        var i = new MessageDialog("查无此地区").ShowAsync();
                    }
                    else
                    {
                        JArray ja       = (JArray)jo["geocodes"];
                        string location = ja[0]["location"].ToString();
                        currentCity = ja[0]["formatted_address"].ToString();

                        string url2 = "http://restapi.amap.com/v3/staticmap?key=5fd3b8bd943a505ccfec387943bba945&zoom=10&size=731*458&traffic=1&location=" + location;
                        HttpResponseMessage response = await client.GetAsync(url2);

                        BitmapImage bitmap = new BitmapImage();
                        Stream      stream = await response.Content.ReadAsStreamAsync();

                        IInputStream inputStream = stream.AsInputStream();
                        using (IRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream())
                        {
                            using (IOutputStream outputStream = randomAccessStream.GetOutputStreamAt(0))
                            {
                                await RandomAccessStream.CopyAsync(inputStream, outputStream);

                                randomAccessStream.Seek(0);
                                bitmap.SetSource(randomAccessStream);
                                map.Source = bitmap;
                            }
                        }
                    }
                }
            }
        }
Пример #33
0
        private static async Task <RTIHttpContent> CreateRequestContentAsync(HttpRequestMessage request, HttpRequestHeaderCollection rtHeaderCollection)
        {
            HttpContent content = request.Content;

            RTIHttpContent      rtContent;
            ArraySegment <byte> buffer;

            // If we are buffered already, it is more efficient to send the data directly using the buffer with the
            // WinRT HttpBufferContent class than using HttpStreamContent. This also avoids issues caused by
            // a design limitation in the System.Runtime.WindowsRuntime System.IO.NetFxToWinRtStreamAdapter.
            if (content.TryGetBuffer(out buffer))
            {
                rtContent = new RTHttpBufferContent(buffer.Array.AsBuffer(), (uint)buffer.Offset, (uint)buffer.Count);
            }
            else
            {
                Stream contentStream = await content.ReadAsStreamAsync().ConfigureAwait(false);

                if (contentStream is RTIInputStream)
                {
                    rtContent = new RTHttpStreamContent((RTIInputStream)contentStream);
                }
                else if (contentStream is MemoryStream)
                {
                    var memStream = contentStream as MemoryStream;
                    if (memStream.TryGetBuffer(out buffer))
                    {
                        rtContent = new RTHttpBufferContent(buffer.Array.AsBuffer(), (uint)buffer.Offset, (uint)buffer.Count);
                    }
                    else
                    {
                        byte[] byteArray = memStream.ToArray();
                        rtContent = new RTHttpBufferContent(byteArray.AsBuffer(), 0, (uint)byteArray.Length);
                    }
                }
                else
                {
                    rtContent = new RTHttpStreamContent(contentStream.AsInputStream());
                }
            }

            // RTHttpBufferContent constructor automatically adds a Content-Length header. RTHttpStreamContent does not.
            // Clear any 'Content-Length' header added by the RTHttp*Content objects. We need to clear that now
            // and decide later whether we need 'Content-Length' or 'Transfer-Encoding: chunked' headers based on the
            // .NET HttpRequestMessage and Content header collections.
            rtContent.Headers.ContentLength = null;

            // Deal with conflict between 'Content-Length' vs. 'Transfer-Encoding: chunked' semantics.
            // Desktop System.Net allows both headers to be specified but ends up stripping out
            // 'Content-Length' and using chunked semantics.  The WinRT APIs throw an exception so
            // we need to manually strip out the conflicting header to maintain app compatibility.
            if (request.Headers.TransferEncodingChunked.HasValue && request.Headers.TransferEncodingChunked.Value)
            {
                content.Headers.ContentLength = null;
            }
            else
            {
                // Trigger delayed header generation via TryComputeLength. This code is needed due to an outstanding
                // bug in HttpContentHeaders.ContentLength. See GitHub Issue #5523.
                content.Headers.ContentLength = content.Headers.ContentLength;
            }

            foreach (KeyValuePair <string, IEnumerable <string> > headerPair in content.Headers)
            {
                foreach (string value in headerPair.Value)
                {
                    if (!rtContent.Headers.TryAppendWithoutValidation(headerPair.Key, value))
                    {
                        // rtContent headers are restricted to a white-list of allowed headers, while System.Net.HttpClient's content headers
                        // will allow custom headers.  If something is not successfully added to the content headers, try adding them to the standard headers.
                        bool success = rtHeaderCollection.TryAppendWithoutValidation(headerPair.Key, value);
                        Debug.Assert(success);
                    }
                }
            }
            return(rtContent);
        }
 // Summary:
 //     Upload files by output stream.
 //
 // Parameters:
 //  sourceFolderId:
 //      The id of the place you want to upload.
 //
 //  fileName:
 //      The name you want to use after upload.
 //
 // Returns:
 //     The StorageFolder where you downloaded folder.
 public async Task <bool> UploadFileStreamAsync(string folderIdToStore, string fileName, Stream outstream)
 {
     //ProgressBar progressBar = new ProgressBar();
     //progressBar.Value = 0;
     //var progressHandler = new Progress<LiveOperationProgress>(
     //    (progress) => { progressBar.Value = progress.ProgressPercentage; });
     System.Threading.CancellationTokenSource ctsUpload = new System.Threading.CancellationTokenSource();
     try
     {
         //LiveOperationResult result = await this.LiveClient
         //    .UploadAsync(folderIdToStore, fileName, outstream, OverwriteOption.Overwrite, ctsUpload.Token, progressHandler);
         LiveOperationResult result = await this.LiveClient.BackgroundUploadAsync(folderIdToStore, fileName, outstream.AsInputStream(), OverwriteOption.Overwrite);
     }
     catch
     {
         ctsUpload.Cancel();
         throw new ShareException(fileName, ShareException.ShareType.UPLOAD);
     }
     return(true);
 }
Пример #35
0
        private async void LoadStrokesFromStream(Stream stream)
        {
            await inkManager.LoadAsync(stream.AsInputStream());

            needToRedrawInkSurface = true;
        }
Пример #36
0
        private async Task <string> GetHashForFileAsync(ListedItem fileItem, string nameOfAlg, CancellationToken token, IProgress <float> progress, IShellPage associatedInstance)
        {
            HashAlgorithmProvider algorithmProvider = HashAlgorithmProvider.OpenAlgorithm(nameOfAlg);
            BaseStorageFile       file = await StorageItemHelpers.ToStorageItem <BaseStorageFile>((fileItem as ShortcutItem)?.TargetPath ?? fileItem.ItemPath, associatedInstance);

            if (file == null)
            {
                return("");
            }

            Stream stream = await FilesystemTasks.Wrap(() => file.OpenStreamForReadAsync());

            if (stream == null)
            {
                return("");
            }

            uint capacity;
            var  inputStream         = stream.AsInputStream();
            bool isProgressSupported = false;

            try
            {
                var cap = (long)(0.5 * stream.Length) / 100;
                if (cap >= uint.MaxValue)
                {
                    capacity = uint.MaxValue;
                }
                else
                {
                    capacity = Convert.ToUInt32(cap);
                }
                isProgressSupported = true;
            }
            catch (NotSupportedException)
            {
                capacity = 64 * 1024;
            }

            Windows.Storage.Streams.Buffer buffer = new Windows.Storage.Streams.Buffer(capacity);
            var hash = algorithmProvider.CreateHash();

            while (!token.IsCancellationRequested)
            {
                await inputStream.ReadAsync(buffer, capacity, InputStreamOptions.None);

                if (buffer.Length > 0)
                {
                    hash.Append(buffer);
                }
                else
                {
                    break;
                }
                if (stream.Length > 0)
                {
                    progress?.Report(isProgressSupported ? (float)stream.Position / stream.Length * 100.0f : 20);
                }
            }
            inputStream.Dispose();
            stream.Dispose();
            if (token.IsCancellationRequested)
            {
                return("");
            }
            return(CryptographicBuffer.EncodeToHexString(hash.GetValueAndReset()).ToLower());
        }
Пример #37
0
        /// <summary>
        /// Starts an asynchronous WritePages operation as soon as the parallel
        /// operation semaphore becomes available.
        /// </summary>
        /// <param name="pageData">Data to be uploaded</param>
        /// <param name="offset">Offset within the page blob</param>
        /// <returns>A task that represents the asynchronous write operation.</returns>
        private async Task WritePagesAsync(Stream pageData, long offset, string contentMD5)
        {
            this.noPendingWritesEvent.Increment();
            await this.parallelOperationSemaphore.WaitAsync();
            Task writePagesTask = this.pageBlob.WritePagesAsync(pageData.AsInputStream(), offset, contentMD5, this.accessCondition, this.options, this.operationContext).AsTask().ContinueWith(task =>
            {
                if (task.Exception != null)
                {
                    this.lastException = task.Exception;
                }

                this.noPendingWritesEvent.Decrement();
                this.parallelOperationSemaphore.Release();
            });
        }
Пример #38
0
 public IInputStream GetInputStreamAt(ulong position)
 {
     //THANKS Microsoft! This is GREATLY appreciated!
     internstream.Position = (long)position;
     return(internstream.AsInputStream());
 }
Пример #39
0
        /// <summary>
        /// Starts an asynchronous PutBlock operation as soon as the parallel
        /// operation semaphore becomes available.
        /// </summary>
        /// <param name="blockData">Data to be uploaded</param>
        /// <param name="blockId">Block ID</param>
        /// <returns>A task that represents the asynchronous write operation.</returns>
        private async Task WriteBlockAsync(Stream blockData, string blockId, string blockMD5)
        {
            this.noPendingWritesEvent.Increment();
            await this.parallelOperationSemaphore.WaitAsync();
            Task putBlockTask = this.blockBlob.PutBlockAsync(blockId, blockData.AsInputStream(), blockMD5, this.accessCondition, this.options, this.operationContext).AsTask().ContinueWith(task =>
            {
                if (task.Exception != null)
                {
                    this.lastException = task.Exception;
                }

                this.noPendingWritesEvent.Decrement();
                this.parallelOperationSemaphore.Release();
            });
        }
Пример #40
-1
        public async Task<long> UploadFileAsync( string fileName, Stream fileContent )
        {
            var client = new HttpClient();
            foreach ( var pair in _headers.Current )
            {
                client.DefaultRequestHeaders.Add( pair.Key, pair.Value );
            }

            string downloadUrl = _settings.Configuration.ServerBaseUrl + PluginName;
            var uri = new Uri( downloadUrl, UriKind.Absolute );

            var streamContent = new HttpStreamContent( fileContent.AsInputStream() );
            var content = new HttpMultipartFormDataContent
            {
                { streamContent, FileContentName },
            };
            // It's important to set this here and not before;
            // HttpMultipartFormDataContent overwrites the headers of its contents.
            streamContent.Headers.ContentDisposition.FileName = fileName;
            var response = await client.PostAsync( uri, content );
            if ( response.StatusCode == HttpStatusCode.ProxyAuthenticationRequired )
            {
                throw new AuthenticationRequiredException();
            }
            response.EnsureSuccessStatusCode();
            var responseStream = await response.Content.ReadAsInputStreamAsync();

            var serializer = new DataContractJsonSerializer( typeof( CloudPrintUploadResponse ) );
            var responseObj = (CloudPrintUploadResponse) serializer.ReadObject( responseStream.AsStreamForRead() );
            return responseObj.DocumentId;
        }