Exemplo n.º 1
0
        private void beginRequestOutput()
        {
            try
            {
                using (Stream requestStream = request.GetRequestStream())
                {
                    reportForwardProgress();
                    requestBody.Position = 0;
                    byte[] buff = new byte[buffer_size];
                    int    read;
                    int    totalRead = 0;
                    while ((read = requestBody.Read(buff, 0, buffer_size)) > 0)
                    {
                        reportForwardProgress();
                        requestStream.Write(buff, 0, read);
                        requestStream.Flush();

                        totalRead += read;
                        UploadProgress?.Invoke(this, totalRead, request.ContentLength);
                    }
                }

                beginResponse();
            }
            catch (Exception e)
            {
                Complete(e);
            }
        }
Exemplo n.º 2
0
        private void UploadData(byte[] data)
        {
            SerialPort.ReadTimeout = 2000;
            try
            {
                Message?.Invoke(this, "Starting upload");
                for (var i = 0; i < Math.Ceiling((double)data.Length / 4096d); i++)
                {
                    SerialPort.Write(data, i * 4096, Math.Min(4096, data.Length - i * 4096));
                    SerialPort.BaseStream.Flush();

                    int d = 0;
                    try
                    {
                        d = SerialPort.ReadByte();
                    }
                    catch { }

                    if (d != 5)
                    {
                        Message?.Invoke(this, "Upload error");
                        return;
                    }

                    UploadProgress?.Invoke(this, (double)i / Math.Ceiling((double)data.Length / 4096d));
                }
            }
            catch
            {
                Message?.Invoke(this, "Upload error");
                return;
            }

            Message?.Invoke(this, "Upload successfull");
        }
Exemplo n.º 3
0
        /// <summary>
        /// upload blob; will continue from where it left off if a previous upload was already in progress
        /// </summary>
        /// <param name="uploadUrl">blob upload url</param>
        /// <param name="blobStream">blob stream to be uploaded; must allow Length, ReadAsync operations. Seek operation must be available for resumed uploads.</param>
        /// <param name="state"></param>
        /// <param name="cancellationToken">cancellation token to stop the asynchronous action</param>
        /// <returns>Returns true if upload is complete; false otherwise</returns>
        public async Task <bool> Upload(Uri uploadUrl, Stream blobStream, object state, CancellationToken cancellationToken = default)
        {
            var headResult = await _tusCore.Head(uploadUrl, cancellationToken);

            long offset = long.Parse(headResult["Upload-Offset"]);
            long length = blobStream.Length;

            var tusUploadFileContext = new TusUploadContext(length, offset, uploadUrl, state);

            while (!cancellationToken.IsCancellationRequested)
            {
                if (offset == length)
                {
                    UploadFinish?.Invoke(this, tusUploadFileContext);
                    return(true);
                }

                if (blobStream.Position != offset)
                {
                    blobStream.Seek(offset, SeekOrigin.Begin);
                }

                int chunkSize = _tusClientOptions.GetChunkUploadSize(this, tusUploadFileContext);
                chunkSize = (int)Math.Min(chunkSize, length - offset);
                byte[] buffer    = new byte[chunkSize];
                var    readCount = await blobStream.ReadAsync(buffer, 0, chunkSize);

                var uploadResult = await _tusCore.Patch(uploadUrl, buffer, offset, cancellationToken);

                offset = long.Parse(uploadResult["Upload-Offset"]);
                tusUploadFileContext.UploadedSize = offset;
                UploadProgress?.Invoke(this, tusUploadFileContext);
            }
            return(false);
        }
 public void DoSomeUpload()
 {
     if (UploadProgress != null)
     {
         UploadEventArgs e = new UploadEventArgs();
         e.BytesSoFar    = 123f;
         e.TotalToUpload = 100000f;
         UploadProgress.Invoke(this, e);
     }
 }
Exemplo n.º 5
0
        public void UploadFile(Stream bodyStream, string relativePath, int bufferSize = RECOMMENDED_BUFFER_SIZE)
        {
            //var request = NewRequest(WebRequestMethods.Ftp.UploadFile);
            var request = NewRequest(relativePath, FtpVerb.STOR);

            request.ContentLength = bodyStream.Length;
            using (var stream = request.GetRequestStream())
            {
                bodyStream.ScanAndWriteTo(stream, bufferSize, (writeTarget, buffer, totalWrittenLength) =>
                {
                    UploadProgress?.Invoke(this, totalWrittenLength, bodyStream.Length);
                });
            }
        }
Exemplo n.º 6
0
        public void Upload(string ComPort, byte[] data, int uploadBaudrate = 115200)
        {
            UploadProgress?.Invoke(this, 0);

            this.SerialPort = new SerialPort(ComPort);
            try
            {
                try
                {
                    this.SerialPort.Open();
                }
                catch (Exception ex)
                {
                    Message?.Invoke(this, "Unable to open Serial Port " + ComPort);
                    return;
                }
                NextionInfos model = null;
                try
                {
                    model = DetectNextion();
                }
                catch
                {
                }

                if (model != null)
                {
                    Message?.Invoke(this, "Nextion found " + model.Model);
                    SwitchToUploadMode(data, uploadBaudrate);
                    UploadData(data);
                }
                else
                {
                    Message?.Invoke(this, "Nextion not found");
                }
            }
            finally
            {
                try
                {
                    SerialPort.Close();
                }
                catch
                {
                }
            }
        }
Exemplo n.º 7
0
        private UploadStatus UploadData(byte[] data)
        {
            SerialPort.ReadTimeout  = 2000;
            SerialPort.WriteTimeout = 5000;
            try
            {
                if (CancelRequested)
                {
                    return(UploadStatus.Cancel);
                }

                Message?.Invoke(this, "Starting upload");
                for (var i = 0; i < Math.Ceiling((double)data.Length / 4096d); i++)
                {
                    if (CancelRequested)
                    {
                        return(UploadStatus.Cancel);
                    }

                    SerialPort.Write(data, i * 4096, Math.Min(4096, data.Length - i * 4096));
                    SerialPort.BaseStream.Flush();

                    int d = 0;
                    try
                    {
                        d = SerialPort.ReadByte();
                    }
                    catch { }

                    if (d != 5)
                    {
                        Message?.Invoke(this, "Upload error");
                        return(UploadStatus.Error);
                    }

                    UploadProgress?.Invoke(this, (double)i / Math.Ceiling((double)data.Length / 4096d));
                }
            }
            catch
            {
                Message?.Invoke(this, "Upload error");
                return(UploadStatus.Error);
            }

            Message?.Invoke(this, "Upload finished");
            return(UploadStatus.Ok);
        }
Exemplo n.º 8
0
        private void perform()
        {
            Aborted = false;
            abortRequest();

            PrePerform();

            try
            {
                reportForwardProgress();
                threadPool.QueueWorkItem(checkTimeoutLoop);

                requestBody = new MemoryStream();

                switch (Method)
                {
                case HttpMethod.GET:
                    Debug.Assert(Files.Count == 0);

                    StringBuilder requestParameters = new StringBuilder();
                    foreach (var p in Parameters)
                    {
                        requestParameters.Append($@"{p.Key}={p.Value}&");
                    }

                    request        = CreateWebRequest(requestParameters.ToString().TrimEnd('&'));
                    request.Method = @"GET";
                    break;

                case HttpMethod.POST:
                    request        = CreateWebRequest();
                    request.Method = @"POST";

                    if (Parameters.Count + Files.Count == 0)
                    {
                        rawContent?.WriteTo(requestBody);
                        request.ContentType = ContentType;
                        requestBody.Flush();
                        break;
                    }

                    const string boundary = @"-----------------------------28947758029299";

                    request.ContentType = $@"multipart/form-data; boundary={boundary}";

                    foreach (KeyValuePair <string, string> p in Parameters)
                    {
                        requestBody.WriteLineExplicit($@"--{boundary}");
                        requestBody.WriteLineExplicit($@"Content-Disposition: form-data; name=""{p.Key}""");
                        requestBody.WriteLineExplicit();
                        requestBody.WriteLineExplicit(p.Value);
                    }

                    foreach (KeyValuePair <string, byte[]> p in Files)
                    {
                        requestBody.WriteLineExplicit($@"--{boundary}");

                        requestBody.WriteLineExplicit($@"Content-Disposition: form-data; name=""{p.Key}""; filename=""{p.Key}""");
                        requestBody.WriteLineExplicit(@"Content-Type: application/octet-stream");
                        requestBody.WriteLineExplicit();
                        requestBody.Write(p.Value, 0, p.Value.Length);
                        requestBody.WriteLineExplicit();
                    }

                    requestBody.WriteLineExplicit($@"--{boundary}--");
                    requestBody.Flush();
                    break;
                }

                request.UserAgent = @"osu!";
                request.KeepAlive = useFallbackPath != true;
                request.Host      = Url.Split('/')[2];
                request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
                request.ReadWriteTimeout       = System.Threading.Timeout.Infinite;
                request.Timeout = Timeout; //todo: make sure this works correctly for long-lasting transfers.

                foreach (KeyValuePair <string, string> h in Headers)
                {
                    request.Headers.Add(h.Key, h.Value);
                }

                ResponseStream = CreateOutputStream();

                switch (Method)
                {
                case HttpMethod.GET:
                    //GETs are easy
                    beginResponse();
                    break;

                case HttpMethod.POST:
                    request.ContentLength = requestBody.Length;

                    UploadProgress?.Invoke(this, 0, request.ContentLength);
                    reportForwardProgress();

                    beginRequestOutput();
                    break;
                }
            }
            catch (Exception e)
            {
                Complete(e);
            }
        }
Exemplo n.º 9
0
 private void MessageHandler_HttpSendProgress(object sender, HttpProgressEventArgs e) => UploadProgress?.Invoke(e.ProgressPercentage);
Exemplo n.º 10
0
        protected virtual void perform()
        {
            Aborted = false;
            abortRequest();

            try
            {
                reportForwardProgress();
                threadPool.QueueWorkItem(checkTimeoutLoop);

                Request        = CreateWebRequest();
                ResponseStream = CreateOutputStream();

                Request.UserAgent = @"osu!";
                Request.KeepAlive = useFallbackPath != true;
                Request.Host      = Url.Split('/')[2];
                Request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
                Request.ReadWriteTimeout       = System.Threading.Timeout.Infinite;
                Request.Timeout = System.Threading.Timeout.Infinite;

                foreach (KeyValuePair <string, string> h in Headers)
                {
                    Request.Headers.Add(h.Key, h.Value);
                }

                if (Parameters.Count + Files.Count > 0)
                {
                    const string boundary = @"-----------------------------28947758029299";

                    Request.ContentType = $@"multipart/form-data; boundary={boundary}";

                    foreach (KeyValuePair <string, string> p in Parameters)
                    {
                        requestBody.WriteLineExplicit($@"--{boundary}");
                        requestBody.WriteLineExplicit($@"Content-Disposition: form-data; name=""{p.Key}""");
                        requestBody.WriteLineExplicit();
                        requestBody.WriteLineExplicit(p.Value);
                    }

                    foreach (KeyValuePair <string, byte[]> p in Files)
                    {
                        requestBody.WriteLineExplicit($@"--{boundary}");

                        requestBody.WriteLineExplicit($@"Content-Disposition: form-data; name=""{p.Key}""; filename=""{p.Key}""");
                        requestBody.WriteLineExplicit(@"Content-Type: application/octet-stream");
                        requestBody.WriteLineExplicit();
                        requestBody.Write(p.Value, 0, p.Value.Length);
                        requestBody.WriteLineExplicit();
                    }

                    requestBody.WriteLineExplicit($@"--{boundary}--");
                    requestBody.Flush();
                }

                if (requestBody.Length != 0)
                {
                    Request.Method        = @"POST";
                    Request.ContentLength = requestBody.Length;

                    UploadProgress?.Invoke(this, 0, Request.ContentLength);
                    reportForwardProgress();

                    beginRequestOutput();
                }
                else
                {
                    //GETs are easy
                    beginResponse();
                }
            }
            catch (Exception e)
            {
                Complete(e);
            }
        }
Exemplo n.º 11
0
        private void internalPerform()
        {
            using (abortToken = new CancellationTokenSource())
                using (timeoutToken = new CancellationTokenSource())
                    using (var linkedToken = CancellationTokenSource.CreateLinkedTokenSource(abortToken.Token, timeoutToken.Token))
                    {
                        try
                        {
                            PrePerform();

                            HttpRequestMessage request;

                            switch (Method)
                            {
                            default:
                                throw new InvalidOperationException($"HTTP method {Method} is currently not supported");

                            case HttpMethod.GET:
                                if (files.Count > 0)
                                {
                                    throw new InvalidOperationException($"Cannot use {nameof(AddFile)} in a GET request. Please set the {nameof(Method)} to POST.");
                                }

                                StringBuilder requestParameters = new StringBuilder();
                                foreach (var p in parameters)
                                {
                                    requestParameters.Append($@"{p.Key}={p.Value}&");
                                }
                                string requestString = requestParameters.ToString().TrimEnd('&');

                                request = new HttpRequestMessage(System.Net.Http.HttpMethod.Get, string.IsNullOrEmpty(requestString) ? Url : $"{Url}?{requestString}");
                                break;

                            case HttpMethod.POST:
                                request = new HttpRequestMessage(System.Net.Http.HttpMethod.Post, Url);

                                Stream postContent;

                                if (rawContent != null)
                                {
                                    if (parameters.Count > 0)
                                    {
                                        throw new InvalidOperationException($"Cannot use {nameof(AddRaw)} in conjunction with {nameof(AddParameter)}");
                                    }
                                    if (files.Count > 0)
                                    {
                                        throw new InvalidOperationException($"Cannot use {nameof(AddRaw)} in conjunction with {nameof(AddFile)}");
                                    }

                                    postContent         = new MemoryStream();
                                    rawContent.Position = 0;
                                    rawContent.CopyTo(postContent);
                                    postContent.Position = 0;
                                }
                                else
                                {
                                    if (!string.IsNullOrEmpty(ContentType) && ContentType != form_content_type)
                                    {
                                        throw new InvalidOperationException($"Cannot use custom {nameof(ContentType)} in a POST request.");
                                    }

                                    ContentType = form_content_type;

                                    var formData = new MultipartFormDataContent(form_boundary);

                                    foreach (var p in parameters)
                                    {
                                        formData.Add(new StringContent(p.Value), p.Key);
                                    }

                                    foreach (var p in files)
                                    {
                                        var byteContent = new ByteArrayContent(p.Value);
                                        byteContent.Headers.Add("Content-Type", "application/octet-stream");
                                        formData.Add(byteContent, p.Key, p.Key);
                                    }

                                    postContent = formData.ReadAsStreamAsync().Result;
                                }

                                requestStream = new LengthTrackingStream(postContent);
                                requestStream.BytesRead.ValueChanged += v =>
                                {
                                    reportForwardProgress();
                                    UploadProgress?.Invoke(v, contentLength);
                                };

                                request.Content = new StreamContent(requestStream);
                                if (!string.IsNullOrEmpty(ContentType))
                                {
                                    request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(ContentType);
                                }
                                break;
                            }

                            if (!string.IsNullOrEmpty(Accept))
                            {
                                request.Headers.Accept.TryParseAdd(Accept);
                            }

                            foreach (var kvp in headers)
                            {
                                request.Headers.Add(kvp.Key, kvp.Value);
                            }

                            reportForwardProgress();
                            using (request)
                                response = client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, linkedToken.Token).Result;

                            ResponseStream = CreateOutputStream();

                            switch (Method)
                            {
                            case HttpMethod.GET:
                                //GETs are easy
                                beginResponse(linkedToken.Token);
                                break;

                            case HttpMethod.POST:
                                reportForwardProgress();
                                UploadProgress?.Invoke(0, contentLength);

                                beginResponse(linkedToken.Token);
                                break;
                            }
                        }
                        catch (Exception) when(timeoutToken.IsCancellationRequested)
                        {
                            Complete(new WebException($"Request to {Url} timed out after {timeSinceLastAction / 1000} seconds idle (read {responseBytesRead} bytes).", WebExceptionStatus.Timeout));
                        }
                        catch (Exception) when(abortToken.IsCancellationRequested)
                        {
                            Complete(new WebException($"Request to {Url} aborted by user.", WebExceptionStatus.RequestCanceled));
                        }
                        catch (Exception e)
                        {
                            Complete(e);
                            throw;
                        }
                    }
        }
Exemplo n.º 12
0
 void DoUploadProgress(string title, long sent, long total)
 {
     UploadProgress?.Invoke(this, new UploadProgressEventArgs(title, sent, total));
 }
        /// <summary>
        /// Main entry point for uploading data to Cycles.
        /// </summary>
        protected bool UploadData()
        {
            if (CancelRender)
            {
                return(false);
            }
            Database.CalculateClippingObjects();

            UploadProgress?.Invoke(this, new UploadProgressEventArgs(0.1f, "Start data upload"));

            if (CancelRender)
            {
                return(false);
            }

            // linear workflow & gamma changes
            Database.UploadGammaChanges();
            UploadProgress?.Invoke(this, new UploadProgressEventArgs(0.2f, "Linear workflow (gamma changes) uploaded"));

            if (CancelRender)
            {
                return(false);
            }

            // environment changes
            Database.UploadEnvironmentChanges();
            UploadProgress?.Invoke(this, new UploadProgressEventArgs(0.3f, "Environments uploaded"));

            if (CancelRender)
            {
                return(false);
            }

            // transforms on objects, no geometry changes
            Database.UploadDynamicObjectTransforms();
            UploadProgress?.Invoke(this, new UploadProgressEventArgs(0.4f, "Dynamic object transforms uploaded"));

            if (CancelRender)
            {
                return(false);
            }

            // viewport changes
            Database.UploadCameraChanges();
            UploadProgress?.Invoke(this, new UploadProgressEventArgs(0.5f, "Viewport uploaded"));

            if (CancelRender)
            {
                return(false);
            }

            // new shaders we've got
            Database.UploadShaderChanges();
            UploadProgress?.Invoke(this, new UploadProgressEventArgs(0.6f, "Shaders uploaded"));

            if (CancelRender)
            {
                return(false);
            }

            // light changes
            Database.UploadLightChanges();
            UploadProgress?.Invoke(this, new UploadProgressEventArgs(0.7f, "Lights uploaded"));

            if (CancelRender)
            {
                return(false);
            }

            // mesh changes (new ones, updated ones)
            Database.UploadMeshChanges();
            UploadProgress?.Invoke(this, new UploadProgressEventArgs(0.8f, "Mesh data uploaded"));

            if (CancelRender)
            {
                return(false);
            }

            // shader changes on objects (replacement)
            Database.UploadObjectShaderChanges();
            UploadProgress?.Invoke(this, new UploadProgressEventArgs(0.9f, "Shader assignments uploaded"));

            if (CancelRender)
            {
                return(false);
            }

            // object changes (new ones, deleted ones)
            Database.UploadObjectChanges();
            UploadProgress?.Invoke(this, new UploadProgressEventArgs(1.0f, "Object changes uploaded"));

            if (CancelRender)
            {
                return(false);
            }

            // done, now clear out our change queue stuff so we're ready for the next time around :)
            Database.ResetChangeQueue();

            if (CancelRender)
            {
                return(false);
            }

            return(true);
        }
Exemplo n.º 14
0
        public void Upload(string ComPort, byte[] data, int uploadBaudrate = 115200, bool reset = false)
        {
            UploadProgress?.Invoke(this, 0);

            this.SerialPort = new SerialPort(ComPort);
            UploadStatus res = UploadStatus.Ok;

            try
            {
                try
                {
                    this.SerialPort.Open();
                }
                catch (Exception ex)
                {
                    Message?.Invoke(this, "Unable to open Serial Port " + ComPort);
                    return;
                }
                NextionInfos model = null;
                try
                {
                    model = DetectNextion();
                }
                catch
                {
                }

                if (model != null)
                {
                    var firmwareVersion = int.Parse(model.FirmwareVersion);

                    Message?.Invoke(this, "Nextion found " + model.Model + " (Firmware version : " + model.FirmwareVersion + ")");

                    if (reset)
                    {
                        Message?.Invoke(this, "Resetting nextion");
                        SendInstruction(SerialPort, "rest");
                        Message?.Invoke(this, "Waiting 4 seconds ...");
                        for (int i = 0; i < 8; i++)
                        {
                            if (CancelRequested)
                            {
                                return;
                            }

                            Thread.Sleep(500);
                        }
                        SerialPort.ReadExisting();
                    }

                    if (firmwareVersion < 130 && uploadBaudrate > 115200)
                    {
                        Message?.Invoke(this, "Nextion firmware does not supports high speed upload, forcing 115200bauds");
                        SwitchToUploadMode(data, 115200);
                    }
                    else if (model.Model[6] == 'T' && uploadBaudrate > 115200)
                    {
                        Message?.Invoke(this, "Basic model does not supports high speed upload, forcing 115200bauds");
                        SwitchToUploadMode(data, 115200);
                    }
                    else
                    {
                        SwitchToUploadMode(data, uploadBaudrate);
                    }

                    res = UploadData(data);
                }
                else
                {
                    if (!CancelRequested)
                    {
                        Message?.Invoke(this, "Nextion not found");
                    }
                }
            }
            finally
            {
                try
                {
                    if (CancelRequested)
                    {
                        Message?.Invoke(this, "Upload canceled");
                    }

                    SerialPort.Close();
                    Message?.Invoke(this, "Resetting arduino micro if required");
                    ResetMicro(ComPort);

                    if (res == UploadStatus.Ok)
                    {
                        Message?.Invoke(this, "Upload finished successfully.");
                    }
                }
                catch
                {
                }
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// Uploads a file
        /// </summary>
        /// <param name="filename">The filename we want to upload</param>
        /// <param name="MD5Checksum">The MD5 checksum of a file</param>
        /// <returns>An Image object that describes the image we uploaded</returns>
        public async Task UploadImageAsync(string filename, string MD5Checksum, CancellationToken token)
        {
            const string url = "https://upload.smugmug.com/";

            try
            {
                var file         = new FileInfo(filename);
                var myWebRequest = (HttpWebRequest)WebRequest.Create(url);

                myWebRequest.Method        = WebRequestMethods.Http.Post;
                myWebRequest.ContentLength = file.Length;
                myWebRequest.UserAgent     = "KHainePhotography PhotoStudioManager v1.0";

                switch (file.Extension.ToLower())
                {
                case "mp4":
                    myWebRequest.ContentType = "video/mp4";
                    break;

                case "jpg":
                    myWebRequest.ContentType = "image/jpeg";
                    break;

                default:
                    myWebRequest.ContentType = "binary/octet-stream";
                    break;
                }

                // Add the authorization header
                myWebRequest.Headers.Add("Authorization", oAuthUtility.GetAuthorizationHeader(Album.Token, myWebRequest.RequestUri.AbsoluteUri));

                myWebRequest.Headers.Add("Content-MD5", MD5Checksum);

                myWebRequest.Headers.Add("X-Smug-ResponseType", "JSON");
                myWebRequest.Headers.Add("X-Smug-Version", "v2");

                myWebRequest.Headers.Add("X-Smug-AlbumUri", Album.Uri);
                myWebRequest.Headers.Add("X-Smug-FileName", file.Name);
                myWebRequest.Headers.Add("X-Smug-Title", Path.GetFileNameWithoutExtension(file.FullName));
                myWebRequest.Headers.Add("X-Smug-Caption", Path.GetFileNameWithoutExtension(file.FullName));

                myWebRequest.Headers.Add("X-Smug-Latitude", "53.457920");
                myWebRequest.Headers.Add("X-Smug-Longitude", "-1.464252");
                myWebRequest.Headers.Add("X-Smug-Altitude", "86");

                myWebRequest.Headers.Add("X-Smug-Pretty", "true");

                //we start reading from the file...

                //we have some elements to set
                //- request time out (compute this for 10 kb/sec speed)
                //- the chunk size to use when uploading (how much data to report after)
                UploadStarted?.Invoke(this, new UploadEventArgs()
                {
                    FileName = file.FullName, PercentComplete = 0
                });

                int timeOut = ((int)file.Length / 1024) * 1000;
                myWebRequest.Timeout                   = timeOut;
                myWebRequest.ReadWriteTimeout          = timeOut;
                myWebRequest.AllowWriteStreamBuffering = true;

                long   howMuchRead = 0;
                byte[] buffer      = new byte[chunkSize];
                int    readSoFar   = 0;

                using (FileStream sr = new FileStream(file.FullName, FileMode.Open, FileAccess.Read))
                {
                    using (var stream = await myWebRequest.GetRequestStreamAsync())
                    {
                        while (howMuchRead < file.Length)
                        {
                            //we try to read a chunk from the file
                            readSoFar    = sr.Read(buffer, 0, chunkSize);
                            howMuchRead += readSoFar;

                            //we now write those files to the web.
                            await stream.WriteAsync(buffer, 0, readSoFar, token);

                            UploadProgress?.Invoke(this, new UploadEventArgs()
                            {
                                FileName = file.FullName, PercentComplete = (float)howMuchRead / (float)file.Length
                            });
                        }
                    }
                }

                var resp = await myWebRequest.GetResponseAsync();

                string rez = string.Empty;
                using (StreamReader ns = new StreamReader(resp.GetResponseStream()))
                {
                    rez = await ns.ReadToEndAsync();
                }

                UploadCompleted?.Invoke(this, new UploadEventArgs()
                {
                    FileName = file.FullName, PercentComplete = (float)howMuchRead / (float)file.Length
                });

                //we deserialize the image
                var response = JsonConvert.DeserializeObject <UploadReponse>(System.Uri.UnescapeDataString(rez));

                if (response.stat != "ok")
                {
                    throw new ApplicationException(response.stat);
                }
            }
            catch (Exception e)
            {
                Debug.Fail(e.Message);
                throw;
            }
        }
Exemplo n.º 16
0
        private HttpWebResponse GetPureResponse(
            string method, string enctype, string url,
            Dictionary <string, object> updata,
            Dictionary <string, object> upfiles)
        {
            if (!Ready(method, enctype, url, updata, upfiles))
            {
                throw new WebException("Instance is not ready to request.");
            }

            method  = method.ToUpper();
            enctype = enctype.ToLower();

            if (updata is null)
            {
                updata = new Dictionary <string, object>();
            }
            if (upfiles is null)
            {
                upfiles = new Dictionary <string, object>();
            }

            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            var    encoding   = Encoding.GetEncoding(StateContainer.Encoding);
            Stream bodyStream = null;

            switch (enctype)
            {
            default:
            case MimeMap.APPLICATION_X_WWW_FORM_URLENCODED:
                var query = new List <string>();
                foreach (var data in updata.Where(x => x.Value != null))
                {
                    var values = NormalizeStringValues(data.Value);
                    query.AddRange(values.Select(value => $"{data.Key}={WebUtility.UrlEncode(value)}"));
                }
                var queryString = query.Join("&");

                if (new[] { HttpVerb.GET, HttpVerb.DELETE }.Contains(method))
                {
                    if (!url.Contains("?"))
                    {
                        url = $"{url}?{queryString}";
                    }
                    else
                    {
                        url = $"{url}&{queryString}";
                    }
                }
                else if (new[] { HttpVerb.POST, HttpVerb.PUT }.Contains(method))
                {
                    bodyStream = new MemoryStream(queryString.Bytes(encoding));
                }
                break;

            case MimeMap.MULTIPART_FORM_DATA:
                var formData = new HttpFormData(encoding);
                foreach (var data in updata.Where(x => x.Value != null))
                {
                    var values = NormalizeStringValues(data.Value);
                    foreach (var value in values)
                    {
                        formData.AddData(data.Key, value.Bytes(encoding));
                    }
                }
                foreach (var file in upfiles)
                {
                    var values = NormalizeStringValues(file.Value);
                    foreach (var value in values)
                    {
                        formData.AddFile(file.Key, Path.GetFileName(value), new FileStream(value, FileMode.Open, FileAccess.Read));
                    }
                }

                bodyStream = formData.GetStream();
                enctype    = formData.ContentType;
                break;

            case MimeMap.APPLICATION_JSON:
                bodyStream = new MemoryStream(JsonConvert.SerializeObject(updata).Bytes(encoding));
                break;
            }

            var request = (HttpWebRequest)WebRequest.Create(new Uri(url));

            {
                StateContainer.Headers.Then(headers =>
                {
                    if (!(headers is null))
                    {
                        foreach (var header in StateContainer.Headers)
                        {
                            request.Headers.Add(header.Key, header.Value);
                        }
                    }
                });

                request.UserAgent             = StateContainer.UserAgent;
                request.Method                = method;
                request.Timeout               = -1;
                request.UseDefaultCredentials = StateContainer.SystemLogin;
                if (StateContainer.UseProxy)
                {
                    if (!string.IsNullOrEmpty(StateContainer.ProxyAddress))
                    {
                        request.Proxy = new WebProxy
                        {
                            Address     = new Uri(StateContainer.ProxyAddress),
                            Credentials = new NetworkCredential
                            {
                                UserName = StateContainer.ProxyUsername,
                                Password = StateContainer.ProxyPassword,
                            }
                        };
                    }
                }
                request.CookieContainer = StateContainer.Cookies;
            }

            if (method == HttpVerb.POST)
            {
                if (!request.Headers.AllKeys.Any(x => x == "Content-Type"))
                {
                    request.ContentType = enctype;
                }

                request.ContentLength = bodyStream.Length;
                using (var stream = request.GetRequestStream())
                {
                    bodyStream.ScanAndWriteTo(stream, RECOMMENDED_BUFFER_SIZE, (writeTarget, buffer, totalWrittenLength) =>
                    {
                        UploadProgress?.Invoke(this, url, totalWrittenLength, bodyStream.Length);
                    });
                }
            }

            HttpWebResponse response = null;

            try
            {
                response = request.GetResponse() as HttpWebResponse;
            }
            catch (WebException ex)
            {
                response = ex.Response as HttpWebResponse;
                if (response is null)
                {
                    throw;
                }
            }
            return(response);
        }