コード例 #1
0
        public async Task UploadMeasureFile()
        {
            using (var http = new System.Net.Http.HttpClient())
            {
                http.DefaultRequestHeaders.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json"));
                http.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.Default.GetBytes("dqm1:Password1!")));

                try
                {
                    using (var stream = System.IO.File.OpenRead(@"C:\work\MeasureSubmission_This_is_the_Second_Best_Metric_ever_-_for_real....json"))
                    {
                        var content = new System.Net.Http.StreamContent(stream);
                        content.Headers.Add("Content-Type", "application/json");

                        var result = await http.PostAsync("https://localhost:44317/api/measures/submit", content);

                        if (!result.IsSuccessStatusCode)
                        {
                            string error = await result.Content.ReadAsStringAsync();

                            Assert.Fail(error);
                            System.Diagnostics.Debug.WriteLine(error);
                        }
                    }
                }
                catch (System.Net.WebException webex)
                {
                    using (var reader = new StreamReader(webex.Response.GetResponseStream()))
                    {
                        Assert.Fail(await reader.ReadToEndAsync());
                        System.Diagnostics.Debug.WriteLine(await reader.ReadToEndAsync());
                    }
                }
            }
        }
コード例 #2
0
        // https://stackoverflow.com/questions/11414987/what-header-should-be-used-for-sending-gzip-compressed-json-from-android-client
        public async System.Threading.Tasks.Task <string> Post()
        {
            string text = null;

            byte[] data = System.IO.File.ReadAllBytes("10G.gzip");

            using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient())
            {
                client.DefaultRequestHeaders.Add("Content-Encoding", "gzip");

                using (System.IO.Stream ms = new System.IO.MemoryStream(data))
                {
                    using (System.Net.Http.StreamContent streamContent = new System.Net.Http.StreamContent(ms))
                    {
                        streamContent.Headers.Add("Content-Encoding", "gzip");
                        streamContent.Headers.ContentLength = ms.Length;

                        System.Uri target = new System.Uri("http://yourServer/yourPage");
                        using (System.Net.Http.HttpRequestMessage requestMessage = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Post, target))
                        {
                            requestMessage.Content = streamContent;
                            using (System.Net.Http.HttpResponseMessage response = await client.SendAsync(requestMessage))
                            {
                                text = await response.Content.ReadAsStringAsync();
                            } // End using response
                        }     // End Using requestMessage
                    }         // End Using streamContent
                }             // End Using ms
            }                 // End Using client

            return(text);
        } // End Sub Post
コード例 #3
0
        private async Task <bool> StartSendingAudioMessageAsync(Chat chat, Matbot.Client.Audio audio)
        {
            try
            {
                using (var httpclient = new System.Net.Http.HttpClient())
                {
                    var uri = "https://api.telegram.org/bot" + Token + "/sendAudio?chat_id=" + chat.TelegramId() + "&title=" + audio.Title + "&duration=" + audio.Duration + "&performer=" + audio.Performer;

                    using (var multipartFormDataContent = new System.Net.Http.MultipartFormDataContent())
                    {
                        var streamContent = new System.Net.Http.StreamContent(audio.AudioStream);
                        streamContent.Headers.Add("Content-Type", "application/octet-stream");
                        streamContent.Headers.Add("Content-Disposition", "form-data; name=\"audio\"; filename=\"" + audio.Title + ".mp3\"");
                        multipartFormDataContent.Add(streamContent, "file", "" + audio.Title + ".mp3");

                        using (var message = await httpclient.PostAsync(HttpUtility.UrlPathEncode(uri), multipartFormDataContent))
                        {
                            var contentString = await message.Content.ReadAsStringAsync();
                        }
                    }
                }
            }
            catch
            {
                return(false);
            }
            return(true);
        }
コード例 #4
0
        } // End Sub Post

        public async System.Threading.Tasks.Task <int?> Get()
        {
            System.Collections.Generic.List <PersonModel> people =
                new System.Collections.Generic.List <PersonModel>
            {
                new PersonModel
                {
                    FirstName = "Test",
                    LastName  = "One",
                    Age       = 25
                },
                new PersonModel
                {
                    FirstName = "Test",
                    LastName  = "Two",
                    Age       = 45
                }
            };

            using (System.Net.Http.HttpClientHandler handler = new System.Net.Http.HttpClientHandler())
            {
                handler.AutomaticDecompression = System.Net.DecompressionMethods.GZip | System.Net.DecompressionMethods.Deflate;
                using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(handler, false))
                {
                    string json               = Newtonsoft.Json.JsonConvert.SerializeObject(people);
                    byte[] jsonBytes          = System.Text.Encoding.UTF8.GetBytes(json);
                    System.IO.MemoryStream ms = new System.IO.MemoryStream();
                    using (System.IO.Compression.GZipStream gzip =
                               new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress, true))
                    {
                        gzip.Write(jsonBytes, 0, jsonBytes.Length);
                    }
                    ms.Position = 0;
                    System.Net.Http.StreamContent content = new System.Net.Http.StreamContent(ms);
                    content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                    content.Headers.ContentEncoding.Add("gzip");
                    System.Net.Http.HttpResponseMessage response = await client.PostAsync("http://localhost:54425/api/Gzipping", content);

                    // System.Collections.Generic.IEnumerable<PersonModel> results = await response.Content.ReadAsAsync<System.Collections.Generic.IEnumerable<PersonModel>>();
                    string result = await response.Content.ReadAsStringAsync();

                    System.Collections.Generic.IEnumerable <PersonModel> results = Newtonsoft.Json.JsonConvert.
                                                                                   DeserializeObject <System.Collections.Generic.IEnumerable <PersonModel> >(result);

                    System.Diagnostics.Debug.WriteLine(string.Join(", ", results));
                }
            }

            return(null);
        }
コード例 #5
0
        public async Task <TransactionModel> PostPicture(Stream stream)
        {
            using (var client = await restClient.CreateAuthenticatedClient())
            {
                var streamContent = new System.Net.Http.StreamContent(stream);
                var result        = await client.PostAsync(Endpoints.Images.Image, streamContent);

                result.EnsureSuccessStatusCode();

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

                var objectResult = JsonConvert.DeserializeObject <TransactionModel>(content);
                return(objectResult);
            }
        }
コード例 #6
0
        /// <summary>
        /// リクエストにファイルデータを追加します。
        /// </summary>
        /// <param name="name"></param>
        /// <param name="path"></param>
        public void AddFilePart(string name, string path)
        {
            var attachment = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data");

            attachment.Name     = name;
            attachment.FileName = System.IO.Path.GetFileName(path);

            var fileContent = new System.Net.Http.StreamContent(System.IO.File.OpenRead(path));

            fileContent.Headers.ContentDisposition = attachment;

            var form = this.GetForm();

            form.Add(fileContent);
        }
コード例 #7
0
        public async Task <bool> UploadThumbnail(string fileID, System.IO.Stream image)
        {
            try
            {
                var IDs      = GetIDs(fileID);
                var httpPath = $"drives/{IDs.DriveID}/items/{IDs.ID}/thumbnails/0/source/content";

                var httpData    = new System.Net.Http.StreamContent(image);
                var httpMessage = await Client.PutAsync(httpPath, httpData);

                if (!httpMessage.IsSuccessStatusCode)
                {
                    throw new Exception(await httpMessage.Content.ReadAsStringAsync());
                }
                return(true);
            }
            catch (Exception ex) { throw new Exception($"Error while uploading thumbnail for file [{fileID}] with oneDrive service", ex); }
        }
コード例 #8
0
        public static async Task <System.Net.Http.HttpContent> CloneHttpContentAsync(System.Net.Http.HttpContent req)
        {
            if (req == null)
            {
                throw new ArgumentException("HTTPContent expected");
            }
            System.Net.Http.HttpContent clone;

            // Copy the request's content (via a MemoryStream) into the cloned object

            System.IO.Stream ms;
            long             contentLen = 99;

            if ((req.Headers != null) && (req.Headers.ContentLength != null))
            {
                contentLen = (long)req.Headers.ContentLength;
            }
            if (contentLen > (50d * OneMBInBytes))
            {
                string tempFN = System.IO.Path.GetTempFileName();
                ms = GetDeleteOnCloseTempFileStream(  );
            }
            else
            {
                ms = new System.IO.MemoryStream( );
            }

            await req.CopyToAsync(ms).ConfigureAwait(false);

            ms.Position = 0;
            clone       = new System.Net.Http.StreamContent(ms);

            // Copy the content headers
            if (req.Headers != null)
            {
                foreach (var h in req.Headers)
                {
                    clone.Headers.Add(h.Key, h.Value);
                }
            }

            return(clone);
        }
コード例 #9
0
        private async Task OnUploadAsync()
        {
            var file = await CrossMedia.Current.PickVideoAsync();


            using (var fs = file.GetStream())
            {
                System.Net.Http.MultipartFormDataContent mfd = new System.Net.Http.MultipartFormDataContent();

                var content = new System.Net.Http.StreamContent(fs);

                mfd.Add(content, "file1", System.IO.Path.GetFileName(file.Path));

                await XamarinFileUploader.FileUploaderService.Instance.StartUpload("1",
                                                                                   "https://secure.800casting.com/upload/uploadtemp",
                                                                                   "POST",
                                                                                   mfd);
            }
        }
コード例 #10
0
        public static void publishResource(
            string prefix,
            System.IO.FileStream fileStream,
            ResourceType resourceType,
            string resourceName,
            string version,
            PublishDepsInfoContainer publishDepsInfo)
        {
            System.Collections.Specialized.NameValueCollection queryString = System.Web.HttpUtility.ParseQueryString(string.Empty);

            queryString["deps"] = publishDepsInfo.serialize();

            string url = resourcePostUrl(prefix, resourceType, resourceName, version) + "?" + queryString.ToString();

            try
            {
                using (var fileContent = new System.Net.Http.StreamContent(fileStream))
                {
                    fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data")
                    {
                        Name     = $"files[{resourceName}]",
                        FileName = resourceName
                    };
                    fileContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");

                    System.Net.Http.HttpResponseMessage statusResult = client.PostAsync(url, fileContent).Result;

                    if (!statusResult.IsSuccessStatusCode)
                    {
                        throw new NetworkUtilsException("Unable to publish: HTTP Error: " + statusResult.StatusCode.ToString());
                    }
                }
            }
            catch (NetworkUtilsException ex)
            {
                throw ex;
            }
            catch (System.Exception)
            {
                throw new NetworkUtilsException($"Unable to publish {resourceType} resource {resourceName} to server");
            }
        }
コード例 #11
0
        System.Net.Http.HttpContent SerializeToContent(object obj)
        {
            var ms = new System.IO.MemoryStream();

            using (var sw = new System.IO.StreamWriter(ms, new UTF8Encoding(false), 1024, true))
                using (var jtw = new Newtonsoft.Json.JsonTextWriter(sw)
                {
                    Formatting = Formatting.None
                })
                {
                    var js = new JsonSerializer();
                    js.Serialize(jtw, obj);
                    jtw.Flush();
                }

            ms.Seek(0, System.IO.SeekOrigin.Begin);
            System.Net.Http.HttpContent httpContent = new System.Net.Http.StreamContent(ms);
            httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

            return(httpContent);
        }
コード例 #12
0
        public void AddAttachment(long workspaceId, long Id, string fileName, string description, System.IO.Stream fileStream)
        {
            string url              = String.Format("{0}/api/rest/v1/workspaces/{1}/items/{2}/attachments", baseUrl, workspaceId, Id);
            var    request          = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Post, url);
            var    scriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();

            var handler = new System.Net.Http.HttpClientHandler();

            handler.CookieContainer = _cookieJar;
            var ressourceName = fileName + DateTime.Now.ToString();

            var httpContent1 = new System.Net.Http.StringContent(scriptSerializer.Serialize(new newAttachment()
            {
                fileName = fileName, description = description, resourceName = fileName
            }));

            httpContent1.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
            byte[] bytes = new byte[fileStream.Length];
            fileStream.Read(bytes, 0, (int)fileStream.Length);
            var memoryStream = new System.IO.MemoryStream(bytes);

            var httpContent2 = new System.Net.Http.StreamContent(memoryStream);

            httpContent2.Headers.ContentDisposition          = new System.Net.Http.Headers.ContentDispositionHeaderValue("*");
            httpContent2.Headers.ContentDisposition.FileName = fileName;
            httpContent2.Headers.ContentDisposition.Size     = memoryStream.Length;
            var multipart = new System.Net.Http.MultipartContent("mixed");

            multipart.Add(httpContent1);
            multipart.Add(httpContent2);
            request.Content = multipart;
            var httpClient = new System.Net.Http.HttpClient(handler);

            httpClient.BaseAddress = new Uri(url);
            var result1 = httpClient.SendAsync(request).Result;
        }
コード例 #13
0
        /// <param name="file">file chunk</param>
        /// <param name="json">json data</param>
        /// <exception cref="SwaggerException">A server side error occurred.</exception>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        public async System.Threading.Tasks.Task <FileResponse> UploadAsync(FileParameter file, string json, System.Threading.CancellationToken cancellationToken)
        {
            var urlBuilder_ = new System.Text.StringBuilder();

            urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/Upload/Upload");

            var client_ = _httpClient;

            try
            {
                using (var request_ = new System.Net.Http.HttpRequestMessage())
                {
                    var boundary_ = System.Guid.NewGuid().ToString();
                    var content_  = new System.Net.Http.MultipartFormDataContent(boundary_);
                    content_.Headers.Remove("Content-Type");
                    content_.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + boundary_);
                    if (file == null)
                    {
                        throw new System.ArgumentNullException("file");
                    }
                    else
                    {
                        var content_file_ = new System.Net.Http.StreamContent(file.Data);
                        if (!string.IsNullOrEmpty(file.ContentType))
                        {
                            content_file_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse(file.ContentType);
                        }
                        content_.Add(content_file_, "file", file.FileName ?? "file");
                    }
                    if (json == null)
                    {
                        throw new System.ArgumentNullException("json");
                    }
                    else
                    {
                        content_.Add(new System.Net.Http.StringContent(ConvertToString(json, System.Globalization.CultureInfo.InvariantCulture)), "json");
                    }
                    request_.Content = content_;
                    request_.Method  = new System.Net.Http.HttpMethod("POST");
                    request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/octet-stream"));

                    PrepareRequest(client_, request_, urlBuilder_);
                    var url_ = urlBuilder_.ToString();
                    request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
                    PrepareRequest(client_, request_, url_);

                    var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);

                    try
                    {
                        var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value);
                        if (response_.Content != null && response_.Content.Headers != null)
                        {
                            foreach (var item_ in response_.Content.Headers)
                            {
                                headers_[item_.Key] = item_.Value;
                            }
                        }

                        ProcessResponse(client_, response_);

                        var status_ = ((int)response_.StatusCode).ToString();
                        if (status_ == "200" || status_ == "206")
                        {
                            var responseStream_ = response_.Content == null ? System.IO.Stream.Null : await response_.Content.ReadAsStreamAsync().ConfigureAwait(false);

                            var fileResponse_ = new FileResponse((int)response_.StatusCode, headers_, responseStream_, null, response_);
                            client_ = null; response_ = null; // response and client are disposed by FileResponse
                            return(fileResponse_);
                        }
                        else
                        if (status_ != "200" && status_ != "204")
                        {
                            var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                            throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", (int)response_.StatusCode, responseData_, headers_, null);
                        }

                        return(default(FileResponse));
                    }
                    finally
                    {
                        if (response_ != null)
                        {
                            response_.Dispose();
                        }
                    }
                }
            }
            finally
            {
            }
        }
コード例 #14
0
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        /// <summary>上传附件</summary>
        /// <param name="saId">景点id</param>
        /// <param name="craId">附件id</param>
        /// <param name="uploadType">上传类型
        /// 0:常规文件
        /// 1:视频封面</param>
        /// <param name="attaType">附件类型(0:图片,1:视频)</param>
        /// <param name="file">文件</param>
        /// <exception cref="ApiException">A server side error occurred.</exception>
        public async System.Threading.Tasks.Task <Tourism.STD.Models.InfoModel <Tourism.STD.Models.Content.TempFileInfoForContent> > UploadTempFileForContentAsync(string saId, string craId, int?uploadType, int?attaType, FileParameter file, System.Threading.CancellationToken cancellationToken)
        {
            var urlBuilder_ = new System.Text.StringBuilder();

            urlBuilder_.Append("Api/Content/UploadTempFileForContent");

            var client_        = _httpClient;
            var disposeClient_ = false;

            try
            {
                using (var request_ = await CreateHttpRequestMessageAsync(cancellationToken).ConfigureAwait(false))
                {
                    var boundary_ = System.Guid.NewGuid().ToString();
                    var content_  = new System.Net.Http.MultipartFormDataContent(boundary_);
                    content_.Headers.Remove("Content-Type");
                    content_.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + boundary_);
                    if (saId != null)
                    {
                        content_.Add(new System.Net.Http.StringContent(ConvertToString(saId, System.Globalization.CultureInfo.InvariantCulture)), "saId");
                    }
                    if (craId != null)
                    {
                        content_.Add(new System.Net.Http.StringContent(ConvertToString(craId, System.Globalization.CultureInfo.InvariantCulture)), "craId");
                    }
                    if (uploadType == null)
                    {
                        throw new System.ArgumentNullException("uploadType");
                    }
                    else
                    {
                        content_.Add(new System.Net.Http.StringContent(ConvertToString(uploadType, System.Globalization.CultureInfo.InvariantCulture)), "uploadType");
                    }
                    if (attaType == null)
                    {
                        throw new System.ArgumentNullException("attaType");
                    }
                    else
                    {
                        content_.Add(new System.Net.Http.StringContent(ConvertToString(attaType, System.Globalization.CultureInfo.InvariantCulture)), "attaType");
                    }
                    if (file != null)
                    {
                        var content_file_ = new System.Net.Http.StreamContent(file.Data);
                        if (!string.IsNullOrEmpty(file.ContentType))
                        {
                            content_file_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse(file.ContentType);
                        }
                        content_.Add(content_file_, "file", file.FileName ?? "file");
                    }
                    request_.Content = content_;
                    request_.Method  = new System.Net.Http.HttpMethod("POST");
                    request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json"));

                    PrepareRequest(client_, request_, urlBuilder_);
                    var url_ = urlBuilder_.ToString();
                    request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
                    PrepareRequest(client_, request_, url_);

                    var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);

                    var disposeResponse_ = true;
                    try
                    {
                        var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value);
                        if (response_.Content != null && response_.Content.Headers != null)
                        {
                            foreach (var item_ in response_.Content.Headers)
                            {
                                headers_[item_.Key] = item_.Value;
                            }
                        }

                        ProcessResponse(client_, response_);

                        var status_ = (int)response_.StatusCode;
                        if (status_ == 200)
                        {
                            var objectResponse_ = await ReadObjectResponseAsync <Tourism.STD.Models.InfoModel <Tourism.STD.Models.Content.TempFileInfoForContent> >(response_, headers_).ConfigureAwait(false);

                            return(objectResponse_.Object);
                        }
                        else
                        {
                            var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                            throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null);
                        }
                    }
                    finally
                    {
                        if (disposeResponse_)
                        {
                            response_.Dispose();
                        }
                    }
                }
            }
            finally
            {
                if (disposeClient_)
                {
                    client_.Dispose();
                }
            }
        }
コード例 #15
0
        /// <summary>Build an image</summary>
        /// <param name="inputStream">A tar archive compressed with one of the following algorithms: identity (no compression), gzip, bzip2, xz.</param>
        /// <param name="dockerfile">Path within the build context to the `Dockerfile`. This is ignored if `remote` is specified and points to an external `Dockerfile`.</param>
        /// <param name="t">A name and optional tag to apply to the image in the `name:tag` format. If you omit the tag the default `latest` value is assumed. You can provide several `t` parameters.</param>
        /// <param name="extrahosts">Extra hosts to add to /etc/hosts</param>
        /// <param name="remote">A Git repository URI or HTTP/HTTPS context URI. If the URI points to a single text file, the file’s contents are placed into a file called `Dockerfile` and the image is built from that file. If the URI points to a tarball, the file is downloaded by the daemon and the contents therein used as the context for the build. If the URI points to a tarball and the `dockerfile` parameter is also specified, there must be a file with the corresponding path inside the tarball.</param>
        /// <param name="q">Suppress verbose build output.</param>
        /// <param name="nocache">Do not use the cache when building the image.</param>
        /// <param name="cachefrom">JSON array of images used for build cache resolution.</param>
        /// <param name="pull">Attempt to pull the image even if an older image exists locally.</param>
        /// <param name="rm">Remove intermediate containers after a successful build.</param>
        /// <param name="forcerm">Always remove intermediate containers, even upon failure.</param>
        /// <param name="memory">Set memory limit for build.</param>
        /// <param name="memswap">Total memory (memory + swap). Set as `-1` to disable swap.</param>
        /// <param name="cpushares">CPU shares (relative weight).</param>
        /// <param name="cpusetcpus">CPUs in which to allow execution (e.g., `0-3`, `0,1`).</param>
        /// <param name="cpuperiod">The length of a CPU period in microseconds.</param>
        /// <param name="cpuquota">Microseconds of CPU time that the container can get in a CPU period.</param>
        /// <param name="buildargs">JSON map of string pairs for build-time variables. Users pass these values at build-time. Docker uses the buildargs as the environment context for commands run via the `Dockerfile` RUN instruction, or for variable expansion in other `Dockerfile` instructions. This is not meant for passing secret values. [Read more about the buildargs instruction.](https://docs.docker.com/engine/reference/builder/#arg)</param>
        /// <param name="shmsize">Size of `/dev/shm` in bytes. The size must be greater than 0. If omitted the system uses 64MB.</param>
        /// <param name="squash">Squash the resulting images layers into a single layer. *(Experimental release only.)*</param>
        /// <param name="labels">Arbitrary key/value labels to set on the image, as a JSON map of string pairs.</param>
        /// <param name="networkmode">Sets the networking mode for the run commands during build. Supported standard values are: `bridge`, `host`, `none`, and `container:<name|id>`. Any other value is taken as a custom network's name to which this container should connect to.</param>
        /// <param name="x_Registry_Config">This is a base64-encoded JSON object with auth configurations for multiple registries that a build may refer to.
        ///
        /// The key is a registry URL, and the value is an auth configuration object, [as described in the authentication section](#section/Authentication). For example:
        ///
        /// ```
        /// {
        ///   "docker.example.com": {
        ///     "username": "******",
        ///     "password": "******"
        ///   },
        ///   "https://index.docker.io/v1/": {
        ///     "username": "******",
        ///     "password": "******"
        ///   }
        /// }
        /// ```
        ///
        /// Only the registry domain name (and port if not the default 443) are required. However, for legacy reasons, the Docker Hub registry must be specified with both a `https://` prefix and a `/v1/` suffix even though Docker will prefer to use the v2 registry API.</param>
        /// <param name="platform">Platform in the format os[/arch[/variant]]</param>
        /// <returns>no error</returns>
        /// <exception cref="SwaggerException">A server side error occurred.</exception>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        public async System.Threading.Tasks.Task <string> ImageBuildAsync(System.IO.Stream inputStream, string dockerfile, string t, string extrahosts, string remote, bool?q, bool?nocache, string cachefrom, string pull, bool?rm, bool?forcerm, int?memory, int?memswap, int?cpushares, string cpusetcpus, int?cpuperiod, int?cpuquota, int?buildargs, int?shmsize, bool?squash, string labels, string networkmode, ContentType?content_type, string x_Registry_Config, string platform, System.Threading.CancellationToken cancellationToken)
        {
            var urlBuilder_ = new System.Text.StringBuilder();

            urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/build?");
            if (dockerfile != null)
            {
                urlBuilder_.Append("dockerfile=").Append(System.Uri.EscapeDataString(ConvertToString(dockerfile, System.Globalization.CultureInfo.InvariantCulture))).Append("&");
            }
            if (t != null)
            {
                urlBuilder_.Append("t=").Append(System.Uri.EscapeDataString(ConvertToString(t, System.Globalization.CultureInfo.InvariantCulture))).Append("&");
            }
            if (extrahosts != null)
            {
                urlBuilder_.Append("extrahosts=").Append(System.Uri.EscapeDataString(ConvertToString(extrahosts, System.Globalization.CultureInfo.InvariantCulture))).Append("&");
            }
            if (remote != null)
            {
                urlBuilder_.Append("remote=").Append(System.Uri.EscapeDataString(ConvertToString(remote, System.Globalization.CultureInfo.InvariantCulture))).Append("&");
            }
            if (q != null)
            {
                urlBuilder_.Append("q=").Append(System.Uri.EscapeDataString(ConvertToString(q, System.Globalization.CultureInfo.InvariantCulture))).Append("&");
            }
            if (nocache != null)
            {
                urlBuilder_.Append("nocache=").Append(System.Uri.EscapeDataString(ConvertToString(nocache, System.Globalization.CultureInfo.InvariantCulture))).Append("&");
            }
            if (cachefrom != null)
            {
                urlBuilder_.Append("cachefrom=").Append(System.Uri.EscapeDataString(ConvertToString(cachefrom, System.Globalization.CultureInfo.InvariantCulture))).Append("&");
            }
            if (pull != null)
            {
                urlBuilder_.Append("pull=").Append(System.Uri.EscapeDataString(ConvertToString(pull, System.Globalization.CultureInfo.InvariantCulture))).Append("&");
            }
            if (rm != null)
            {
                urlBuilder_.Append("rm=").Append(System.Uri.EscapeDataString(ConvertToString(rm, System.Globalization.CultureInfo.InvariantCulture))).Append("&");
            }
            if (forcerm != null)
            {
                urlBuilder_.Append("forcerm=").Append(System.Uri.EscapeDataString(ConvertToString(forcerm, System.Globalization.CultureInfo.InvariantCulture))).Append("&");
            }
            if (memory != null)
            {
                urlBuilder_.Append("memory=").Append(System.Uri.EscapeDataString(ConvertToString(memory, System.Globalization.CultureInfo.InvariantCulture))).Append("&");
            }
            if (memswap != null)
            {
                urlBuilder_.Append("memswap=").Append(System.Uri.EscapeDataString(ConvertToString(memswap, System.Globalization.CultureInfo.InvariantCulture))).Append("&");
            }
            if (cpushares != null)
            {
                urlBuilder_.Append("cpushares=").Append(System.Uri.EscapeDataString(ConvertToString(cpushares, System.Globalization.CultureInfo.InvariantCulture))).Append("&");
            }
            if (cpusetcpus != null)
            {
                urlBuilder_.Append("cpusetcpus=").Append(System.Uri.EscapeDataString(ConvertToString(cpusetcpus, System.Globalization.CultureInfo.InvariantCulture))).Append("&");
            }
            if (cpuperiod != null)
            {
                urlBuilder_.Append("cpuperiod=").Append(System.Uri.EscapeDataString(ConvertToString(cpuperiod, System.Globalization.CultureInfo.InvariantCulture))).Append("&");
            }
            if (cpuquota != null)
            {
                urlBuilder_.Append("cpuquota=").Append(System.Uri.EscapeDataString(ConvertToString(cpuquota, System.Globalization.CultureInfo.InvariantCulture))).Append("&");
            }
            if (buildargs != null)
            {
                urlBuilder_.Append("buildargs=").Append(System.Uri.EscapeDataString(ConvertToString(buildargs, System.Globalization.CultureInfo.InvariantCulture))).Append("&");
            }
            if (shmsize != null)
            {
                urlBuilder_.Append("shmsize=").Append(System.Uri.EscapeDataString(ConvertToString(shmsize, System.Globalization.CultureInfo.InvariantCulture))).Append("&");
            }
            if (squash != null)
            {
                urlBuilder_.Append("squash=").Append(System.Uri.EscapeDataString(ConvertToString(squash, System.Globalization.CultureInfo.InvariantCulture))).Append("&");
            }
            if (labels != null)
            {
                urlBuilder_.Append("labels=").Append(System.Uri.EscapeDataString(ConvertToString(labels, System.Globalization.CultureInfo.InvariantCulture))).Append("&");
            }
            if (networkmode != null)
            {
                urlBuilder_.Append("networkmode=").Append(System.Uri.EscapeDataString(ConvertToString(networkmode, System.Globalization.CultureInfo.InvariantCulture))).Append("&");
            }
            if (platform != null)
            {
                urlBuilder_.Append("platform=").Append(System.Uri.EscapeDataString(ConvertToString(platform, System.Globalization.CultureInfo.InvariantCulture))).Append("&");
            }
            urlBuilder_.Length--;

            var client_ = this._injectedClient;

            try
            {
                using (var request_ = new System.Net.Http.HttpRequestMessage())
                {
                    if (content_type != null)
                    {
                        request_.Headers.TryAddWithoutValidation("Content-type", ConvertToString(content_type, System.Globalization.CultureInfo.InvariantCulture));
                    }
                    if (x_Registry_Config != null)
                    {
                        request_.Headers.TryAddWithoutValidation("X-Registry-Config", ConvertToString(x_Registry_Config, System.Globalization.CultureInfo.InvariantCulture));
                    }
                    var content_ = new System.Net.Http.StreamContent(inputStream);
                    content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/octet-stream");
                    request_.Content             = content_;
                    request_.Method = new System.Net.Http.HttpMethod("POST");

                    PrepareRequest(client_, request_, urlBuilder_);
                    var url_ = urlBuilder_.ToString();
                    request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
                    PrepareRequest(client_, request_, url_);

                    var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);

                    try
                    {
                        var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value);
                        foreach (var item_ in response_.Content.Headers)
                        {
                            headers_[item_.Key] = item_.Value;
                        }

                        ProcessResponse(client_, response_);

                        var status_ = ((int)response_.StatusCode).ToString();
                        if (status_ == "200")
                        {
                            var responseData_ = await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                            return(responseData_);
                        }
                        else
                        if (status_ == "400")
                        {
                            var responseData_ = await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                            throw new SwaggerException("Bad parameter", status_, responseData_, headers_, null);
                        }
                        else
                        if (status_ == "500")
                        {
                            var responseData_ = await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                            throw new SwaggerException("server error", status_, responseData_, headers_, null);
                        }
                        else
                        if (status_ != "200" && status_ != "204")
                        {
                            var responseData_ = await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                            throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", status_, responseData_, headers_, null);
                        }

                        throw new SwaggerException("unknown status code", status_, "", headers_, null);
                    }
                    finally
                    {
                        if (response_ != null)
                        {
                            response_.Dispose();
                        }
                    }
                }
            }
            finally
            {
                if (client_ != null)
                {
                    client_.Dispose();
                }
            }
        }
コード例 #16
0
        /// <summary>
        /// 发送数据
        /// </summary>
        /// <returns></returns>
        string _Send(Uri uri, string method)
        {
            if (IsMultipart)
            {
                method = "POST";
            }
            //HttpWebRequest request = null;
            if (String.IsNullOrEmpty(UserAgent) == false)
            {
                _WebClient.DefaultRequestHeaders.Add("User-Agent", UserAgent);
            }
            switch (method)
            {
            case "POST":

                using (System.IO.MemoryStream memory = new System.IO.MemoryStream())
                {
                    var writer = new System.IO.StreamWriter(memory);
                    if (IsMultipart)
                    {
                        for (int i = 0, l = this.PostData.Count; i < l; i++)
                        {
                            var name  = this.PostData.GetKey(i);
                            var value = this.PostData.Get(i);
                            writer.Write("--{0}{3}Content-Disposition: form-data; name=\"{1}\"{3}{3}{2}{3}",
                                         FormBoundary, name, value, _lineBreak);
                        }
                        for (int i = 0, l = this.Count; i < l; i++)
                        {
                            var name  = this.GetKey(i);
                            var value = this.BaseGet(i);
                            if (value is HttpFile)
                            {
                                var file     = value as HttpFile;
                                var filename = file.FileName ?? name;
                                var end      = filename.LastIndexOf('\\');
                                if (end == -1)
                                {
                                    end = filename.LastIndexOf('/');
                                }
                                if (end > 0)
                                {
                                    filename = filename.Substring(end + 1);
                                }
                                writer.Write("--{0}{4}Content-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"{4}Content-Type: {3}{4}{4}",
                                             FormBoundary, name, filename, file.ContentType ?? "application/octet-stream", _lineBreak);
                                writer.Flush();
                                this.Writer(file, writer.BaseStream);
                                writer.Flush();
                                writer.Write(_lineBreak);
                            }
                            else
                            {
                                writer.Write("--{0}{3}Content-Disposition: form-data; name=\"{1}\"{3}{3}{2}{3}",
                                             FormBoundary, name, this[i], _lineBreak);
                            }
                        }
                        writer.Write("--{0}--", FormBoundary, _lineBreak);
                    }
                    else
                    {
                        //_WebClient.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded; charset=UTF-8";
                        Escape(writer, this.PostData, true);
                        Escape(writer, this, this.PostData.Count == 0);
                    }

                    writer.Flush();
                    memory.Position = 0;
                    var cont = new System.Net.Http.StreamContent(memory);
                    cont.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse(this.IsMultipart ? GetMultipartFormContentType() : "application/x-www-form-urlencoded; charset=UTF-8");
                    //_WebClient.PostAsync()

                    var httpContent = _WebClient.PostAsync(uri, cont).Result.Content;
                    if (httpContent.Headers.ContentEncoding.ToString() == "gzip")
                    {
                        var zip = new System.IO.Compression.GZipStream(httpContent.ReadAsStreamAsync().Result
                                                                       , System.IO.Compression.CompressionMode.Decompress);

                        return(GetResult(zip));
                    }
                    else
                    {
                        return(httpContent.ReadAsStringAsync().Result);
                    }
                }

            default:
                var sb  = new StringBuilder();
                var wsb = new System.IO.StringWriter(sb);
                Escape(wsb, this.PostData, true);
                Escape(wsb, this, this.PostData.Count == 0);
                //  var url = this.GetUrl();
                if (sb.Length > 0)
                {
                    if (String.IsNullOrEmpty(uri.Query))
                    {
                        sb.Insert(0, '?');
                    }
                    else
                    {
                        sb.Insert(0, '&');
                    }
                }
                sb.Insert(0, uri.AbsoluteUri);


                var httpContent2 = _WebClient.GetAsync(sb.ToString()).Result.Content;
                if (httpContent2.Headers.ContentEncoding.ToString() == "gzip")
                {
                    var zip = new System.IO.Compression.GZipStream(httpContent2.ReadAsStreamAsync().Result
                                                                   , System.IO.Compression.CompressionMode.Decompress);

                    return(GetResult(zip));
                }
                else
                {
                    return(httpContent2.ReadAsStringAsync().Result);
                }
            }
        }
コード例 #17
0
        /// <returns>Success</returns>
        /// <exception cref="SwaggerException">A server side error occurred.</exception>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        public async System.Threading.Tasks.Task <DocProof> PutProofDocAsync(FileParameter proofDoc, string bindingId, string citizenIdentifier, System.Threading.CancellationToken cancellationToken)
        {
            var urlBuilder_ = new System.Text.StringBuilder();

            urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/DocProof/PutProofDocs?");
            if (bindingId != null)
            {
                urlBuilder_.Append("bindingId=").Append(System.Uri.EscapeDataString(ConvertToString(bindingId, System.Globalization.CultureInfo.InvariantCulture))).Append("&");
            }
            if (citizenIdentifier != null)
            {
                urlBuilder_.Append("citizenIdentifier=").Append(System.Uri.EscapeDataString(ConvertToString(citizenIdentifier, System.Globalization.CultureInfo.InvariantCulture))).Append("&");
            }
            urlBuilder_.Length--;

            var client_ = _httpClient;

            try
            {
                using (var request_ = new System.Net.Http.HttpRequestMessage())
                {
                    var boundary_ = System.Guid.NewGuid().ToString();
                    var content_  = new System.Net.Http.MultipartFormDataContent(boundary_);
                    content_.Headers.Remove("Content-Type");
                    content_.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + boundary_);
                    if (proofDoc != null)
                    {
                        var content_proofDoc_ = new System.Net.Http.StreamContent(proofDoc.Data);
                        if (!string.IsNullOrEmpty(proofDoc.ContentType))
                        {
                            content_proofDoc_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse(proofDoc.ContentType);
                        }
                        content_.Add(content_proofDoc_, "proofDoc", proofDoc.FileName ?? "proofDoc");
                    }
                    request_.Content = content_;
                    request_.Method  = new System.Net.Http.HttpMethod("POST");
                    request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json"));

                    PrepareRequest(client_, request_, urlBuilder_);
                    var url_ = urlBuilder_.ToString();
                    request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
                    PrepareRequest(client_, request_, url_);

                    var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);

                    try
                    {
                        var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value);
                        if (response_.Content != null && response_.Content.Headers != null)
                        {
                            foreach (var item_ in response_.Content.Headers)
                            {
                                headers_[item_.Key] = item_.Value;
                            }
                        }

                        ProcessResponse(client_, response_);

                        var status_ = ((int)response_.StatusCode).ToString();
                        if (status_ == "200")
                        {
                            var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                            var result_ = default(DocProof);
                            try
                            {
                                result_ = Newtonsoft.Json.JsonConvert.DeserializeObject <DocProof>(responseData_, _settings.Value);
                                return(result_);
                            }
                            catch (System.Exception exception_)
                            {
                                throw new SwaggerException("Could not deserialize the response body.", (int)response_.StatusCode, responseData_, headers_, exception_);
                            }
                        }
                        else
                        if (status_ != "200" && status_ != "204")
                        {
                            var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                            throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", (int)response_.StatusCode, responseData_, headers_, null);
                        }

                        return(default(DocProof));
                    }
                    finally
                    {
                        if (response_ != null)
                        {
                            response_.Dispose();
                        }
                    }
                }
            }
            finally
            {
            }
        }
コード例 #18
0
        public async Task <string> GetRecono([FromForm] string param, [FromForm] string paramImagen)
        {
            //this.infoPopup.ShowOnPageLoad = false;
            try
            {
                string paramImagen2 = JsonConvert.DeserializeObject <string>(paramImagen.ToString());
                System.Net.HttpWebRequest  request       = null;
                System.Net.HttpWebResponse response      = null;
                System.IO.Stream           requestStream = null;
                byte[] bytes     = null;
                string resultado = "";

                byte[] data = System.Convert.FromBase64String(paramImagen2.ToString());

                string url = "https://api.luxand.cloud/photo/search";


                System.Net.ServicePointManager.SecurityProtocol = (System.Net.SecurityProtocolType) 3072;


                System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
                client.DefaultRequestHeaders.Add("token", "f579e24b9b094e4a9eaabf6c5477bd1a");
                Stream fileStream = new MemoryStream(data);
                System.Net.Http.HttpContent fileStreamContent = new System.Net.Http.StreamContent(fileStream);

                using (var formData = new System.Net.Http.MultipartFormDataContent())
                {
                    formData.Add(fileStreamContent, "photo", "file1");
                    var response2 = await client.PostAsync(url, formData);

                    if (!response2.IsSuccessStatusCode)
                    {
                        return(null);
                    }
                    return(await response2.Content.ReadAsStringAsync());
                }


                //bytes = System.Text.Encoding.ASCII.GetBytes("photo=" + data);
                //request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);

                //request.Method = "POST";
                //request.Headers.Add("token", "f579e24b9b094e4a9eaabf6c5477bd1a");

                //request.ContentLength = bytes.Length;
                //request.ContentType = "multipart/form-data";



                //requestStream = request.GetRequestStream();
                //requestStream.Write(bytes, 0, bytes.Length);
                //requestStream.Close();

                //request.Timeout = 15000;

                //response = (System.Net.HttpWebResponse)request.GetResponse();

                //if (response.StatusCode == System.Net.HttpStatusCode.OK)
                //{
                //    System.IO.Stream responseStream = response.GetResponseStream();
                //    System.IO.StreamReader reader = new System.IO.StreamReader(responseStream);
                //    resultado = reader.ReadToEnd();
                //    return resultado;
                //}
            }
            catch (Exception ex)
            {
                return("ERROR");
            }

            return("ERROR");
        }
コード例 #19
0
ファイル: Formdata.cs プロジェクト: tjprescott/autorest
        /// <summary>
        /// Upload file
        /// </summary>
        /// <param name='fileContent'>
        /// File to upload.
        /// </param>
        /// <param name='fileName'>
        /// File name to upload. Name has to be spelled exactly as written here.
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="ErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async System.Threading.Tasks.Task <Microsoft.Rest.HttpOperationResponse <System.IO.Stream> > UploadFileWithHttpMessagesAsync(System.IO.Stream fileContent, string fileName, System.Collections.Generic.Dictionary <string, System.Collections.Generic.List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            if (fileContent == null)
            {
                throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "fileContent");
            }
            if (fileName == null)
            {
                throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "fileName");
            }
            // Tracing
            bool   _shouldTrace  = Microsoft.Rest.ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
                System.Collections.Generic.Dictionary <string, object> tracingParameters = new System.Collections.Generic.Dictionary <string, object>();
                tracingParameters.Add("fileContent", fileContent);
                tracingParameters.Add("fileName", fileName);
                tracingParameters.Add("cancellationToken", cancellationToken);
                Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "UploadFile", tracingParameters);
            }
            // Construct URL
            var _baseUrl = this.Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "formdata/stream/uploadfile").ToString();

            // Create HTTP transport objects
            System.Net.Http.HttpRequestMessage  _httpRequest  = new System.Net.Http.HttpRequestMessage();
            System.Net.Http.HttpResponseMessage _httpResponse = null;
            _httpRequest.Method     = new System.Net.Http.HttpMethod("POST");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            System.Net.Http.MultipartFormDataContent _multiPartContent = new System.Net.Http.MultipartFormDataContent();
            if (fileContent != null)
            {
                System.Net.Http.StreamContent _fileContent = new System.Net.Http.StreamContent(fileContent);
                _fileContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
                System.IO.FileStream _fileContentAsFileStream = fileContent as System.IO.FileStream;
                if (_fileContentAsFileStream != null)
                {
                    System.Net.Http.Headers.ContentDispositionHeaderValue _contentDispositionHeaderValue = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data");
                    _contentDispositionHeaderValue.Name     = "fileContent";
                    _contentDispositionHeaderValue.FileName = _fileContentAsFileStream.Name;
                    _fileContent.Headers.ContentDisposition = _contentDispositionHeaderValue;
                }
                _multiPartContent.Add(_fileContent, "fileContent");
            }
            if (fileName != null)
            {
                System.Net.Http.StringContent _fileName = new System.Net.Http.StringContent(fileName, System.Text.Encoding.UTF8);
                _multiPartContent.Add(_fileName, "fileName");
            }
            _httpRequest.Content = _multiPartContent;
            // Send Request
            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200)
            {
                var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <Error>(_responseContent, this.Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (Newtonsoft.Json.JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new Microsoft.Rest.HttpOperationResponse <System.IO.Stream>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _result.Body = await _httpResponse.Content.ReadAsStreamAsync().ConfigureAwait(false);
            }
            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
コード例 #20
0
        public async Task UploadJsonMeasure()
        {
            var app = new ApplicationFactory();

            using (var scope = app.CreateScope())
                using (var db = scope.ServiceProvider.GetRequiredService <Model.ModelDataContext>())
                {
                    //get the first count metric
                    var metric = db.Metrics.Include(m => m.ResultsType).Where(m => m.ResultsType.Value == "Count" && m.Statuses.OrderByDescending(s => s.CreateOn).First().MetricStatusID == Model.MetricStatus.PublishedID).FirstOrDefault();

                    if (metric == null)
                    {
                        Assert.Fail("There is no published metric to create measures for.");
                    }

                    var rnd = new Random();


                    var measureMeta = new Models.MeasureSubmissionViewModel {
                        MetricID            = metric.ID,
                        ResultsType         = metric.ResultsType.Value,
                        DataSource          = "Unit Test DataSource",
                        Organization        = "Unit Test Organization",
                        Network             = "Developerland",
                        RunDate             = DateTime.Now.Date,
                        DateRangeStart      = DateTime.Now.AddYears(Convert.ToInt32(-100 * rnd.NextDouble())).Date,
                        DateRangeEnd        = DateTime.Now.AddMonths(Convert.ToInt32(-12 * rnd.NextDouble())).Date,
                        SupportingResources = "https://github.com/some-organization/repositoryurl"
                    };

                    List <Models.MeasurementSubmissionViewModel> measurements = new List <Models.MeasurementSubmissionViewModel>();
                    int totalRows = Convert.ToInt32(20 * rnd.NextDouble()) + 1;
                    for (int i = 0; i < totalRows; i++)
                    {
                        measurements.Add(new Models.MeasurementSubmissionViewModel {
                            RawValue = i.ToString(), Definition = i.ToString(), Measure = Convert.ToSingle(100 * rnd.NextDouble())
                        });
                    }
                    float sum = measurements.Sum(m => m.Measure.Value);
                    foreach (var measure in measurements)
                    {
                        measure.Total = sum;
                    }

                    measureMeta.Measures = measurements;

                    using (var ms = new System.IO.MemoryStream())
                    {
                        using (var sw = new System.IO.StreamWriter(ms, Encoding.Default, 1024, true))
                            using (var jw = new Newtonsoft.Json.JsonTextWriter(sw))
                            {
                                var serializer = new Newtonsoft.Json.JsonSerializer();
                                serializer.DateFormatString = "yyyy'-'MM'-'dd";
                                serializer.Formatting       = Newtonsoft.Json.Formatting.None;

                                serializer.Serialize(jw, measureMeta);
                                await jw.FlushAsync();
                            }

                        ms.Seek(0, SeekOrigin.Begin);

                        using (var http = new System.Net.Http.HttpClient())
                        {
                            http.DefaultRequestHeaders.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json"));
                            http.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.Default.GetBytes("dqm1:Password1!")));

                            try
                            {
                                var content = new System.Net.Http.StreamContent(ms);
                                content.Headers.Add("Content-Type", "application/json");

                                var result = await http.PostAsync("https://localhost:44317/api/measures/submit", content);

                                if (result.IsSuccessStatusCode)
                                {
                                    var responseContent = await result.Content.ReadAsStringAsync();
                                }
                                else
                                {
                                    string error = await result.Content.ReadAsStringAsync();

                                    Assert.Fail(error);
                                }
                            }
                            catch (System.Net.WebException webex)
                            {
                                using (var reader = new StreamReader(webex.Response.GetResponseStream()))
                                {
                                    Assert.Fail(await reader.ReadToEndAsync());
                                }
                            }
                        }
                    }
                }
        }
コード例 #21
0
        // [Command(HistogramCommandName), Alias("scoregraph", "scorestats", "statistics"), Summary("Generates a histogram of the given tier's scores for the given image within the given state on the current CyberPatriot leaderboard.")]
        // [Priority(-1)]
        // public Task HistogramCommandAsync([OverrideTypeReader(typeof(LocationTypeReader))] string location, Division div, Tier tier, string imageName) => GenerateHistogramAsync(new ScoreboardFilterInfo(div, tier), imageName, location);


        public async Task GenerateHistogramAsync(ScoreboardFilterInfo filter, string imageName, string locCode)
        {
            using (Context.Channel.EnterTypingState())
            {
                var descBuilder = new System.Text.StringBuilder();
                if (filter.Division.HasValue)
                {
                    descBuilder.Append(' ').Append(filter.Division.Value.ToStringCamelCaseToSpace());
                }
                if (filter.Tier.HasValue)
                {
                    descBuilder.Append(' ').Append(filter.Tier.Value);
                }
                if (imageName != null)
                {
                    throw new NotSupportedException("Per-image histograms are not yet supported.");

                    // unreachable code - not implemented on the data-aggregation/filter side, but this code Should Work:tm: for constructing the title
#pragma warning disable 0162
                    if (descBuilder.Length > 0)
                    {
                        descBuilder.Append(": ");
                    }
                    descBuilder.Append(imageName);
#pragma warning restore 0162
                }

                CompleteScoreboardSummary scoreboard = await ScoreRetrievalService.GetScoreboardAsync(filter).ConfigureAwait(false);

                decimal[] data = scoreboard.TeamList
                                 .Conditionally(locCode != null, tle => tle.Where(t => t.Location == locCode))
                                 // nasty hack
                                 .Select(datum => decimal.TryParse(ScoreRetrievalService.Metadata.FormattingOptions.FormatScore(datum.TotalScore), out decimal d) ? d : datum.TotalScore)
                                 .OrderBy(d => d).ToArray();
                using (var memStr = new System.IO.MemoryStream())
                {
                    await GraphProvider.WriteHistogramPngAsync(data, "Score", "Frequency", datum => datum.ToString("0.0#"), BitmapProvider.Color.Parse("#32363B"), BitmapProvider.Color.Parse("#7289DA"), BitmapProvider.Color.White, BitmapProvider.Color.Gray, memStr).ConfigureAwait(false);

                    memStr.Position = 0;

                    // This shouldn't be necessary, Discord's API supports embedding attached images
                    // BUT discord.net does not, see #796
                    var httpClient       = new System.Net.Http.HttpClient();
                    var imagePostMessage = new System.Net.Http.StreamContent(memStr);
                    imagePostMessage.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/png");
                    Task <System.Net.Http.HttpResponseMessage> uploadUrlResponseTask = httpClient.PutAsync("https://transfer.sh/histogram.png", imagePostMessage);

                    var histogramEmbed = new EmbedBuilder()
                                         .WithTitle("CyberPatriot Score Analysis")
                                         .WithDescription(Utilities.JoinNonNullNonEmpty(" | ", filter.Division?.ToStringCamelCaseToSpace(), filter.Tier, locCode).CoalesceBlank("All Teams"))
                                         .AddInlineField("Teams", data.Length)
                                         .AddInlineField("Mean", $"{data.Average():0.##}")
                                         .AddInlineField("Standard Deviation", $"{data.StandardDeviation():0.##}")
                                         .AddInlineField("First Quartile", $"{data.Take(data.Length / 2).ToArray().Median():0.##}")
                                         .AddInlineField("Median", $"{data.Median():0.##}")
                                         .AddInlineField("Third Quartile", $"{data.Skip(data.Length / 2).ToArray().Median():0.##}")
                                         .AddInlineField("Min Score", $"{data.Min()}")
                                         .AddInlineField("Max Score", $"{data.Max()}")
                                         .WithImageUrl(await(await uploadUrlResponseTask.ConfigureAwait(false)).Content.ReadAsStringAsync().ConfigureAwait(false))
                                         .WithTimestamp(scoreboard.SnapshotTimestamp)
                                         .WithFooter(ScoreRetrievalService.Metadata.StaticSummaryLine);

                    await Context.Channel.SendMessageAsync("", embed : histogramEmbed).ConfigureAwait(false);
                }
            }
        }
コード例 #22
0
        /// <summary>
        /// Adds the provided images to the current project iteration
        /// </summary>
        /// <param name='projectId'>
        /// The project id.
        /// </param>
        /// <param name='imageData'>
        /// </param>
        /// <param name='tagIds'>
        /// The tags ids to associate with the image batch.
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="HttpOperationException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <HttpOperationResponse <CreateImageSummaryModel> > CreateImagesFromDataWithHttpMessagesAsync(System.Guid projectId, IEnumerable <Stream> imageData, IList <Guid> tagIds = default(IList <Guid>), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (imageData == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "imageData");
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("projectId", projectId);
                tracingParameters.Add("tagIds", tagIds);
                tracingParameters.Add("imageData", imageData);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "PostImages", tracingParameters);
            }
            // Construct URL
            var _baseUrl = BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "projects/{projectId}/images/image").ToString();

            _url = _url.Replace("{projectId}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(projectId, SerializationSettings).Trim('"')));
            List <string> _queryParameters = new List <string>();

            if (tagIds != null)
            {
                if (tagIds.Count == 0)
                {
                    _queryParameters.Add(string.Format("tagIds={0}", System.Uri.EscapeDataString(string.Empty)));
                }
                else
                {
                    foreach (var _item in tagIds)
                    {
                        _queryParameters.Add(string.Format("tagIds={0}", System.Uri.EscapeDataString(_item.ToString() ?? string.Empty)));
                    }
                }
            }
            if (_queryParameters.Count > 0)
            {
                _url += "?" + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            var _httpRequest = new System.Net.Http.HttpRequestMessage();

            System.Net.Http.HttpResponseMessage _httpResponse = null;
            _httpRequest.Method     = new System.Net.Http.HttpMethod("POST");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            System.Net.Http.MultipartFormDataContent _multiPartContent = new System.Net.Http.MultipartFormDataContent();
            if (imageData != null)
            {
                foreach (var image in imageData)
                {
                    System.Net.Http.StreamContent _imageData = new System.Net.Http.StreamContent(image);
                    _imageData.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
                    FileStream _imageDataAsFileStream = image as FileStream;
                    if (_imageDataAsFileStream != null)
                    {
                        System.Net.Http.Headers.ContentDispositionHeaderValue _contentDispositionHeaderValue = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data");
                        _contentDispositionHeaderValue.Name     = "imageData";
                        _contentDispositionHeaderValue.FileName = _imageDataAsFileStream.Name;
                        _imageData.Headers.ContentDisposition   = _contentDispositionHeaderValue;
                    }
                    _multiPartContent.Add(_imageData, "imageData");
                }
            }
            _httpRequest.Content = _multiPartContent;
            // Set Credentials
            if (Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200)
            {
                var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                if (_httpResponse.Content != null)
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                }
                else
                {
                    _responseContent = string.Empty;
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new HttpOperationResponse <CreateImageSummaryModel>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = SafeJsonConvert.DeserializeObject <CreateImageSummaryModel>(_responseContent, DeserializationSettings);
                }
                catch (Newtonsoft.Json.JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
コード例 #23
0
        /// <returns>Success</returns>
        /// <exception cref="SwaggerException">A server side error occurred.</exception>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        public async System.Threading.Tasks.Task <JobResult> UploadJobAsync(FileParameter file, string fScriptParams, string scriptFilename, string outputFileFormat, System.Threading.CancellationToken cancellationToken)
        {
            var urlBuilder_ = new System.Text.StringBuilder();

            urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/UploadJob");

            var client_ = _httpClient;

            try
            {
                using (var request_ = new System.Net.Http.HttpRequestMessage())
                {
                    var boundary_ = System.Guid.NewGuid().ToString();
                    var content_  = new System.Net.Http.MultipartFormDataContent(boundary_);
                    content_.Headers.Remove("Content-Type");
                    content_.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + boundary_);
                    if (file != null)
                    {
                        var content_file_ = new System.Net.Http.StreamContent(file.Data);
                        if (!string.IsNullOrEmpty(file.ContentType))
                        {
                            content_file_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse(file.ContentType);
                        }
                        content_.Add(content_file_, "file", file.FileName ?? "file");
                    }
                    if (fScriptParams != null)
                    {
                        content_.Add(new System.Net.Http.StringContent(ConvertToString(fScriptParams, System.Globalization.CultureInfo.InvariantCulture)), "fScriptParams");
                    }
                    if (scriptFilename != null)
                    {
                        content_.Add(new System.Net.Http.StringContent(ConvertToString(scriptFilename, System.Globalization.CultureInfo.InvariantCulture)), "scriptFilename");
                    }
                    if (outputFileFormat != null)
                    {
                        content_.Add(new System.Net.Http.StringContent(ConvertToString(outputFileFormat, System.Globalization.CultureInfo.InvariantCulture)), "outputFileFormat");
                    }
                    request_.Content = content_;
                    request_.Method  = new System.Net.Http.HttpMethod("POST");
                    request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json"));

                    PrepareRequest(client_, request_, urlBuilder_);
                    var url_ = urlBuilder_.ToString();
                    request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
                    PrepareRequest(client_, request_, url_);

                    var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);

                    try
                    {
                        var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value);
                        if (response_.Content != null && response_.Content.Headers != null)
                        {
                            foreach (var item_ in response_.Content.Headers)
                            {
                                headers_[item_.Key] = item_.Value;
                            }
                        }

                        ProcessResponse(client_, response_);

                        var status_ = ((int)response_.StatusCode).ToString();
                        if (status_ == "200")
                        {
                            var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                            var result_ = default(JobResult);
                            try
                            {
                                result_ = Newtonsoft.Json.JsonConvert.DeserializeObject <JobResult>(responseData_, _settings.Value);
                                return(result_);
                            }
                            catch (System.Exception exception_)
                            {
                                throw new SwaggerException("Could not deserialize the response body.", (int)response_.StatusCode, responseData_, headers_, exception_);
                            }
                        }
                        else
                        if (status_ != "200" && status_ != "204")
                        {
                            var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                            throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", (int)response_.StatusCode, responseData_, headers_, null);
                        }

                        return(default(JobResult));
                    }
                    finally
                    {
                        if (response_ != null)
                        {
                            response_.Dispose();
                        }
                    }
                }
            }
            finally
            {
            }
        }