public static async Task <İcraSonuç> RestoranDeğiştir(Restoran restoran)
        {
            try
            {
                using (var istemci = new System.Net.Http.HttpClient())
                {
                    var msj = await istemci.PutAsync(RestoranlarUrl + "/RestoranDeğiştir",
                                                     HazırlaWebYardımcı.JsonİçerikOluştur(restoran));

                    if (msj.Content != null)
                    {
                        return(Newtonsoft.Json.JsonConvert.DeserializeObject <İcraSonuç>(await msj.Content.ReadAsStringAsync()));
                    }
                    else
                    {
                        return(null);
                    }
                }
            }
            catch (Exception ex)
            {
                await HazırlaWebYardımcı.HataKaydet(ex);

                throw ex;
            }
        }
Пример #2
0
        /// <summary>
        /// 將 PUT 要求傳送至指定的 URI
        /// </summary>
        /// <param name="uri">The RequestUri</param>
        /// <param name="httpContent">The HttpContent</param>
        public void Put(Uri uri, System.Net.Http.HttpContent httpContent)
        {
            if (uri == null)
            {
                throw new ArgumentNullException("uri");
            }

            if (httpContent == null)
            {
                throw new ArgumentNullException("httpContent");
            }

            using (var client = new System.Net.Http.HttpClient())
            {
                client.MaxResponseContentBufferSize = this.MaxResponseContentBufferSize;

                client.Timeout = this.Timeout;

                this.SetHttpHeader(client);

                this.SetMediaTypeHeaderValue(client);

                var response = client.PutAsync(uri, httpContent).Result;

                this.ResponseBody = response.Content.ReadAsStringAsync().Result;

                this.HttpStatusCode = response.StatusCode;
            }
        }
        public static async Task <İcraSonuç> MenüDeğiştir(Menü menü)
        {
            try
            {
                using (var istemci = new System.Net.Http.HttpClient())
                {
                    var msj = await istemci.PutAsync(MenülerUrl, BisiparişWebYardımcı.JsonİçerikOluştur(menü));

                    if (msj.Content != null)
                    {
                        return(Newtonsoft.Json.JsonConvert.DeserializeObject <İcraSonuç>(await msj.Content.ReadAsStringAsync()));
                    }
                    else
                    {
                        return(null);
                    }
                }
            }
            catch (Exception ex)
            {
                await BisiparişWebYardımcı.GünlükKaydet(OlaySeviye.Hata, ex);

                throw ex;
            }
        }
        public async Task CompressedRequestHandler_PutAsync_CompressesContent()
        {
            var requestUriString = "http://sometestdomain.com/someendpoint";

            var mh = new MockMessageHandler();

            mh.AddFixedResponse("PUT", new Uri(requestUriString), new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Created));

            var handler = new CompressedRequestHandler(mh);
            var client  = new System.Net.Http.HttpClient(handler);

            var uncompressedContent = "A compressible string. A compressible string. A compressible string. A compressible string.";
            var result = await client.PutAsync(requestUriString, new System.Net.Http.StringContent(uncompressedContent)).ConfigureAwait(false);

            var modifiedContent = await mh.Requests.Last().Content.ReadAsStringAsync().ConfigureAwait(false);

            Assert.IsTrue(modifiedContent.Length < uncompressedContent.Length);

            var stream = await mh.Requests.Last().Content.ReadAsStreamAsync().ConfigureAwait(false);

            var decompressStream    = new System.IO.Compression.GZipStream(stream, System.IO.Compression.CompressionMode.Decompress);
            var reader              = new System.IO.StreamReader(decompressStream);
            var decompressedContent = reader.ReadToEnd();

            Assert.AreEqual(uncompressedContent, decompressedContent);
        }
Пример #5
0
        private void startElasticsearchWatcherClient()
        {
            System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient();
            var content = new System.Net.Http.StringContent("{\"trigger\":{\"schedule\":{\"interval\":\"10s\"}},\"input\":{\"search\":{\"request\":{\"body\":{\"query\":{\"term\":{\"alarmType\":{\"value\":\"critical\"}}}}}}},\"condition\":{\"always\":{}},\"actions\":{\"webAction\":{\"webhook\":{\"port\":5000,\"host\":\"localhost\",\"path\":\"/api/WatcherEvents/CriticalAlarm\",\"method\":\"post\",\"headers\":{\"Content-Type\":\"application/json;charset=utf-8\"},\"body\":\"{{ctx.payload.hits.total}}\"}}}}");

            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

            var response = httpClient.PutAsync("http://localhost:9200/_watcher/watch/critical-alarm-watch", content).Result;
        }
Пример #6
0
        public static async Task <System.Net.Http.HttpResponseMessage> PutAsJsonAsync <T>(this System.Net.Http.HttpClient client, string requestUrl, T value)
        {
            var data     = System.Text.Json.JsonSerializer.Serialize(value);
            var content  = new System.Net.Http.StringContent(data, System.Text.Encoding.UTF8, "application/json");
            var response = await client.PutAsync(requestUrl, content);

            return(response);
            //return await System.Text.Json.JsonSerializer.SerializeAsync<T>(jsonString, options);
        }
        public IActionResult Edit(Guid id, [Bind("Id,Name,FathersName,Age")] Models.Student student)
        {
            System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
            client.BaseAddress = new Uri(_configuration.GetValue <string>("AppConfig:Url"));
            System.Net.Http.ObjectContent content = new System.Net.Http.ObjectContent(typeof(Models.Student), student, new System.Net.Http.Formatting.JsonMediaTypeFormatter());
            var result = client.PutAsync("/api/StudentService/", content).Result;

            return(RedirectToAction("Index"));
        }
Пример #8
0
        // 목표 온도 설정
        // 9 ~ 32 (℉ = ℃ * 1.8000 + 32.00)
        public async Task <string> SetTemperature(ThermostatDevice device, double target, string scale = "C")
        {
            AuthorizationError = false;

            string tsc = ("C" == scale) ? "target_temperature_c" : "target_temperature_f";

            string api = string.Format("https://developer-api.nest.com/devices/thermostats/{0}?auth={1}",
                                       device.device_id, AuthToken);

            string body = "{\"" + tsc + "\": " + target.ToString() + ", \"temperature_scale\": \"" + scale + "\"}";

            using (System.Net.Http.HttpClient client = HttpApiClient())
            {
                try
                {
                    System.Net.Http.HttpResponseMessage response = await client.PutAsync(new Uri(api), new System.Net.Http.StringContent(body));

                    Uri url = response.Headers.Location;
                    response = await client.PutAsync(url, new System.Net.Http.StringContent(body));

                    string responseContent = await response.Content.ReadAsStringAsync();

                    if (responseContent.Contains("error"))
                    {
                        if (responseContent.Contains("authorization code expired") || responseContent.Contains("authorization code not found"))
                        {
                            AuthorizationError = true;
                        }

                        ErrorMessage = Parse.ErrorMessage(responseContent);
                        return(ErrorMessage);
                    }

                    return(responseContent);
                }
                catch (Exception ex)
                {
                    ErrorMessage = ex.Message;
                }

                return(ErrorMessage);
            }
        }
Пример #9
0
        public async Task <string> SetFanOff(ThermostatDevice device)
        {
            AuthorizationError = false;

            string api = string.Format("https://developer-api.nest.com/devices/thermostats/{0}?auth={1}",
                                       device.device_id, AuthToken);

            string body = "{\"fan_timer_active\": false}";

            using (System.Net.Http.HttpClient client = HttpApiClient())
            {
                try
                {
                    System.Net.Http.HttpResponseMessage response = await client.PutAsync(new Uri(api), new System.Net.Http.StringContent(body));

                    Uri url = response.Headers.Location;
                    response = await client.PutAsync(url, new System.Net.Http.StringContent(body));

                    string responseContent = await response.Content.ReadAsStringAsync();

                    if (responseContent.Contains("error"))
                    {
                        if (responseContent.Contains("authorization code expired") || responseContent.Contains("authorization code not found"))
                        {
                            AuthorizationError = true;
                        }

                        ErrorMessage = Parse.ErrorMessage(responseContent);
                        return(ErrorMessage);
                    }

                    return(responseContent);
                }
                catch (Exception ex)
                {
                    ErrorMessage = ex.Message;
                }

                return(ErrorMessage);
            }
        }
Пример #10
0
        private async Task <T> serverPut <T>(string apiAddress, string content)
        {
            string address = serverAddress + apiAddress;

            System.Net.Http.StringContent c = new System.Net.Http.StringContent(content);
            c.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
            var result = await client.PutAsync(address, c);

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

            return(JsonConvert.DeserializeObject <T>(resultContent));
        }
        public async Task CompressedRequestHandler_PutAsync_WorksWithNullContent()
        {
            var requestUriString = "http://sometestdomain.com/someendpoint";

            var mh = new MockMessageHandler();

            mh.AddFixedResponse("PUT", new Uri(requestUriString), new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Created));

            var handler = new CompressedRequestHandler(mh);
            var client  = new System.Net.Http.HttpClient(handler);

            var result = await client.PutAsync(requestUriString, null).ConfigureAwait(false);

            result.EnsureSuccessStatusCode();
        }
        public async Task CompressedRequestHandler_PutAsync_SetsContentEncodingHeader()
        {
            var requestUriString = "http://sometestdomain.com/someendpoint";

            var mh = new MockMessageHandler();

            mh.AddFixedResponse("PUT", new Uri(requestUriString), new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Created));

            var handler = new CompressedRequestHandler(mh);
            var client  = new System.Net.Http.HttpClient(handler);

            var uncompressedContent = "A compressible string. A compressible string. A compressible string. A compressible string.";
            var result = await client.PutAsync(requestUriString, new System.Net.Http.StringContent(uncompressedContent)).ConfigureAwait(false);

            Assert.AreEqual("gzip", mh.Requests.Last().Content.Headers.ContentEncoding.First());
        }
Пример #13
0
        async public Task <string> getWatchingPut()
        {
            util.debugWriteLine("watching put" + util.getMainSubStr(isSub, true));
            for (var i = 0; i < 3; i++)
            {
                try {
                    var handler = new System.Net.Http.HttpClientHandler();
                    handler.UseCookies      = true;
                    handler.CookieContainer = container;
                    var http = new System.Net.Http.HttpClient(handler);
                    handler.UseProxy = false;
                    http.DefaultRequestHeaders.Add("X-Frontend-Id", "91");
                    http.DefaultRequestHeaders.Add("X-Connection-Environment", "ethernet");
                    http.DefaultRequestHeaders.Add("Host", "api.cas.nicovideo.jp");
                    http.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0");
                    http.DefaultRequestHeaders.Add("Accept", "application/json");

                    var contentStr = "{\"actionTrackId\":\"" + actionTrackId + "\",\"isBroadcaster\":\"" + isBroadcaster.ToString().ToLower() + "\"}";

                    http.Timeout = TimeSpan.FromSeconds(5);

                    var content = new System.Net.Http.StringContent(contentStr);
                    content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

                    //var _res = await http.PutAsync(watchingUrl, content);


                    var t = http.PutAsync(watchingUrl, content);
                    t.Wait();
                    var _res = t.Result;
                    var res  = await _res.Content.ReadAsStringAsync();

                    //			var a = _res.Headers;

                    //			if (res.IndexOf("login_status = 'login'") < 0) return null;

                    //				cc = handler.CookieContainer;

                    return(res);
                    //				return cc;
                } catch (Exception e) {
                    util.debugWriteLine("watching put exception " + e.Message + e.StackTrace + e.Source + e.TargetSite + util.getMainSubStr(isSub, true));
//					return null;
                }
            }
            return(null);
        }
Пример #14
0
        private async void button2_Click(object sender, EventArgs e)
        {
            if (Uri.IsWellFormedUriString(url_txt.Text, UriKind.Absolute))
            {
                if (Get.Checked)
                {
                    if (json_txt.Text.Length == 0)
                    {
                        System.Net.Http.HttpRequestMessage  requestMessage = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, url_txt.Text);
                        System.Net.Http.HttpClient          http           = new System.Net.Http.HttpClient();
                        System.Net.Http.HttpResponseMessage httpResponse   = await http.SendAsync(requestMessage);

                        preview_txt.Text = httpResponse.Content.ReadAsStringAsync().Result;
                        label8.Text      = httpResponse.StatusCode.ToString();
                    }
                    else
                    {
                        MessageBox.Show("You can not send json-query to GET method", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                if (Post.Checked)
                {
                    var data = new System.Net.Http.StringContent(json_txt.Text, Encoding.UTF8, "application/json");
                    System.Net.Http.HttpClient          http         = new System.Net.Http.HttpClient();
                    System.Net.Http.HttpResponseMessage httpResponse = await http.PostAsync(url_txt.Text, data);

                    preview_txt.Text = httpResponse.Content.ReadAsStringAsync().Result;
                }
                if (Put.Checked)
                {
                    var data = new System.Net.Http.StringContent(json_txt.Text, Encoding.UTF8, "application/json");
                    System.Net.Http.HttpClient          http         = new System.Net.Http.HttpClient();
                    System.Net.Http.HttpResponseMessage httpResponse = await http.PutAsync(url_txt.Text, data);

                    preview_txt.Text = httpResponse.Content.ReadAsStringAsync().Result;
                }
                if (Delete.Checked)
                {
                    System.Net.Http.HttpRequestMessage  requestMessage = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Delete, url_txt.Text);
                    System.Net.Http.HttpClient          http           = new System.Net.Http.HttpClient();
                    System.Net.Http.HttpResponseMessage httpResponse   = await http.SendAsync(requestMessage);

                    preview_txt.Text = httpResponse.Content.ReadAsStringAsync().Result;
                }
            }
        }
        async void ButtonUpdateRestToDo_Click(object sender, RoutedEventArgs e)
        {
            var      button = (Button)sender;
            ToDoItem todo   = ((ToDoItem)button.DataContext);

            // Verify that the new description of the To-Do is different from the previous description:
            string previousDescription = todo.Description;
            string newDescription      = RestToDoTextBox.Text.Replace("\"", "'");

            if (newDescription == previousDescription)
            {
                MessageBox.Show("To update the To-Do, please enter a different text in the field above, and then click the 'Update' button.");
                return;
            }

            button.Content   = "Please wait...";
            button.IsEnabled = false;

            try
            {
                string data = string.Format(@"{{""OwnerId"": ""{0}"",""Id"": ""{1}"",""Description"": ""{2}""}}", _ownerId, todo.Id, RestToDoTextBox.Text.Replace("\"", "'"));
#if !OPENSILVER
                var webClient = new WebClient();
                webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
                webClient.Encoding = Encoding.UTF8;
                string response = await webClient.UploadStringTaskAsync("http://cshtml5-rest-sample.azurewebsites.net/api/Todo/" + todo.Id.ToString(), "PUT", data);
#else
                //Note: it seems WebClient is not supported (despite existing) in Blazor so we use HttpClient instead
                var httpClient = new System.Net.Http.HttpClient();
                await httpClient.PutAsync("http://cshtml5-rest-sample.azurewebsites.net/api/Todo/" + todo.Id.ToString(),
                                          new System.Net.Http.StringContent(data, Encoding.UTF8, "application/json"));
#endif

                await RefreshRestToDos();
            }
            catch (Exception ex)
            {
                MessageBox.Show("ERROR: " + ex.ToString());
            }

            button.IsEnabled = true;
            button.Content   = "Update";
        }
Пример #16
0
        public Task <bool> PutData(string url, List <KeyValuePair <string, string> > data)
        {
            TaskCompletionSource <bool> TCS = new TaskCompletionSource <bool>();

            var uri = new Uri(url);

            System.Net.Http.HttpClient  httpClient = new System.Net.Http.HttpClient();
            System.Net.Http.HttpContent content    = new System.Net.Http.FormUrlEncodedContent(data);

            string text = string.Empty;


            Task <System.Net.Http.HttpResponseMessage> response = httpClient.PutAsync(uri, content);

            response.ContinueWith(r =>
            {
                TCS.SetResult(r.Result.IsSuccessStatusCode);
            }, TaskContinuationOptions.OnlyOnRanToCompletion);

            return(TCS.Task);
        }
        public static async Task <İcraSonuç> KafeDeğiştir(Kafe kafe)
        {
            try
            {
                using (var istemci = new System.Net.Http.HttpClient())
                {
                    var msj = await istemci.PutAsync(KafelerUrl + "/KafeDeğiştir", JsonİçerikOluştur(kafe));

                    if (msj.Content != null)
                    {
                        return(Newtonsoft.Json.JsonConvert.DeserializeObject <İcraSonuç>(await msj.Content.ReadAsStringAsync()));
                    }
                    else
                    {
                        return(null);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Пример #18
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            var deferral = taskInstance.GetDeferral();

            if (taskInstance.TriggerDetails is ToastNotificationActionTriggerDetail details)
            {
                string[] segments = details.Argument.Split('/');
                var      count    = segments.Count();
                if (count > 0)
                {
                    var creds = (new Windows.Security.Credentials.PasswordVault()).FindAllByResource("Token").FirstOrDefault();
                    if (creds == null)
                    {
                        return;
                    }
                    creds.RetrievePassword();
                    var token = creds.Password;

                    if (segments[0] == "relationship")
                    {
                        if (count > 2)
                        {
                            if (segments[1] == "accept")
                            {
                                //accept friend request
                                using (var http = new System.Net.Http.HttpClient())
                                {
                                    System.Net.Http.HttpContent content = new System.Net.Http.StringContent("{}");
                                    content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                                    http.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(token);
                                    await http.PutAsync("https://discordapp.com/api/v6/users/@me/relationships/" + segments[2], content);

                                    ToastNotificationManager.History.Remove(segments[2], "relationship");
                                }
                            }
                            else if (segments[1] == "decline")
                            {
                                //decline friend request
                                using (var http = new System.Net.Http.HttpClient())
                                {
                                    http.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(token);
                                    await http.DeleteAsync("https://discordapp.com/api/v6/users/@me/relationships/" + segments[2]);

                                    ToastNotificationManager.History.Remove(segments[2], "relationship");
                                }
                            }
                        }
                    }
                    else if (segments[0] == "send")
                    {
                        using (var http = new System.Net.Http.HttpClient())
                        {
                            string response = CleanForJson(details.UserInput["Reply"].ToString());
                            if (response == null)
                            {
                                return;
                            }
                            System.Net.Http.HttpContent content = new System.Net.Http.StringContent("{\"content\":\"" + response + "\"}");
                            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                            http.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(token);
                            await http.PostAsync("https://discordapp.com/api/v6/channels/" + segments[1] + "/messages", content);

                            ToastNotificationManager.History.Remove(segments[2], "Mention");
                        }
                    }
                }
            }
            deferral.Complete();
        }
Пример #19
0
        public async System.Threading.Tasks.Task <System.Text.Json.JsonElement> SendFilesAsync(System.Collections.Generic.Dictionary <System.String, System.Collections.Generic.List <SoftmakeAll.SDK.Communication.REST.File> > FormData)
        {
            if (System.String.IsNullOrWhiteSpace(this.URL))
            {
                throw new System.Exception(SoftmakeAll.SDK.Communication.REST.EmptyURLErrorMessage);
            }

            this.HasRequestErrors = false;

            using (System.Net.Http.HttpClient HttpClient = new System.Net.Http.HttpClient())
            {
                if (this.Headers.Count > 0)
                {
                    foreach (System.Collections.Generic.KeyValuePair <System.String, System.String> Header in this.Headers)
                    {
                        HttpClient.DefaultRequestHeaders.Add(Header.Key, Header.Value);
                    }
                }
                this.AddAuthorizationHeader(HttpClient);

                using (System.Net.Http.MultipartFormDataContent MultipartFormDataContent = new System.Net.Http.MultipartFormDataContent())
                {
                    if ((FormData != null) && (FormData.Count > 0))
                    {
                        foreach (System.Collections.Generic.KeyValuePair <System.String, System.Collections.Generic.List <SoftmakeAll.SDK.Communication.REST.File> > Item in FormData)
                        {
                            if ((!(System.String.IsNullOrWhiteSpace(Item.Key))) && (Item.Value != null) && (Item.Value.Any()))
                            {
                                foreach (SoftmakeAll.SDK.Communication.REST.File File in Item.Value)
                                {
                                    System.Net.Http.ByteArrayContent ByteArrayContent = new System.Net.Http.ByteArrayContent(File.Contents);
                                    if (!(System.String.IsNullOrWhiteSpace(File.ContentType)))
                                    {
                                        ByteArrayContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(File.ContentType);
                                    }
                                    MultipartFormDataContent.Add(ByteArrayContent, Item.Key, File.Name);
                                }
                            }
                        }
                    }

                    if (this.Timeout > 0)
                    {
                        HttpClient.Timeout = System.TimeSpan.FromMilliseconds(this.Timeout);
                    }

                    try
                    {
                        System.Net.Http.HttpResponseMessage HttpResponseMessage;
                        switch (this.Method)
                        {
                        case "PATCH":
                        {
                            HttpResponseMessage = await HttpClient.PatchAsync(this.URL, MultipartFormDataContent);

                            break;
                        }

                        case "POST":
                        {
                            HttpResponseMessage = await HttpClient.PostAsync(this.URL, MultipartFormDataContent);

                            break;
                        }

                        case "PUT":
                        {
                            HttpResponseMessage = await HttpClient.PutAsync(this.URL, MultipartFormDataContent);

                            break;
                        }

                        default: throw new System.NotSupportedException($"Method {this.Method} is not supported for sending files. Plese use PATCH, POST or PUT.");
                        }
                        this._StatusCode      = HttpResponseMessage.StatusCode;
                        this.HasRequestErrors = false;

                        System.Byte[] APIResult = await HttpResponseMessage.Content.ReadAsByteArrayAsync();

                        if (APIResult == null)
                        {
                            return(new System.Text.Json.JsonElement());
                        }

                        return(System.Text.Encoding.UTF8.GetString(APIResult).ToJsonElement());
                    }
                    catch (System.Exception ex)
                    {
                        this.HasRequestErrors = ex.InnerException == null;
                        this._StatusCode      = System.Net.HttpStatusCode.InternalServerError;
                        return(new System.Text.Json.JsonElement());
                    }
                }
            }
        }
Пример #20
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);
                }
            }
        }
Пример #21
0
        public async System.Threading.Tasks.Task <System.Net.Http.HttpResponseMessage> SendAsync(string requestMethod, string target, string jsonBody, int timeoutSeconds = 60)
        {
            string requestDateSecret = "HRWORKS" + this.secretAccessKey;

            System.DateTime now = System.DateTime.Now;

            string requestTimestampAsText = string.Format("{0:yyyyMMdd}T{0:HHmmss}Z", now.ToUniversalTime());
            string requestDateAsText      = string.Format("{0:yyyyMMdd}", now.ToUniversalTime());

            // Creating the canonical request
            string canonicalRequest = GetCanonicalRequest(Host, requestMethod, @"/", target, requestTimestampAsText, jsonBody);

            // Creating the string to sign
            System.Text.StringBuilder stringSignatur = new System.Text.StringBuilder();
            stringSignatur.Append(SignatureAlgorithmIdentifier);
            stringSignatur.Append("\n");
            stringSignatur.Append(requestTimestampAsText);
            stringSignatur.Append("\n");
            stringSignatur.Append(GetSha256Hash(canonicalRequest.ToString()));

            // Creating the string to sign
            byte[] requestDateSign = GetHMACSHA256Hash(requestDateAsText, System.Text.Encoding.ASCII.GetBytes(requestDateSecret));
            byte[] realmSign       = GetHMACSHA256Hash(RealmIdentifier, requestDateSign);
            byte[] closingSign     = GetHMACSHA256Hash(ClosingString, realmSign);

            byte[] stringSign = GetHMACSHA256Hash(stringSignatur.ToString(), closingSign);

            string newSignature = GetHex(stringSign);

            System.Text.StringBuilder credential = new System.Text.StringBuilder();

            credential.AppendFormat("Credential={0}/{1}, ", System.Net.WebUtility.UrlEncode(AccessKey), RealmIdentifier);
            credential.Append("SignedHeaders=content-type;host;x-hrworks-date;x-hrworks-target, ");
            credential.AppendFormat("Signature={0}", newSignature);

            using (System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient())
            {
                TimeSpan timeout = TimeSpan.FromSeconds(timeoutSeconds);

                try
                {
                    System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Ssl3 | System.Net.SecurityProtocolType.Tls | System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls12;
                }
                catch (Exception)
                {
                }

                string url = string.Format("https://{0}", Host);

                httpClient.BaseAddress = new Uri(url);
                httpClient.DefaultRequestHeaders.Accept.Clear();
                httpClient.Timeout = timeout;
                httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                httpClient.DefaultRequestHeaders.Date = new System.DateTimeOffset(now);
                httpClient.DefaultRequestHeaders.Add(HeaderXHRworksDate, requestTimestampAsText);
                httpClient.DefaultRequestHeaders.Add(HeaderXHRworksTarget, target);

                System.Net.Http.Headers.AuthenticationHeaderValue authenticationHeaderValue = new System.Net.Http.Headers.AuthenticationHeaderValue(SignatureAlgorithmIdentifier, credential.ToString());
                httpClient.DefaultRequestHeaders.Authorization = authenticationHeaderValue;

                System.Net.Http.StringContent body = new System.Net.Http.StringContent(jsonBody, Encoding.UTF8, "application/json");

                System.Net.Http.HttpResponseMessage httpResponseMessage = null;

                switch (requestMethod.ToUpper())
                {
                case RequestMethod.Post:
                    httpResponseMessage = await httpClient.PostAsync(url, body);

                    break;

                case RequestMethod.Put:
                    httpResponseMessage = await httpClient.PutAsync(url, body);

                    break;

                case RequestMethod.Get:
                    httpResponseMessage = await httpClient.GetAsync(url);

                    break;

                case RequestMethod.Delete:
                    httpResponseMessage = await httpClient.DeleteAsync(url);

                    break;
                }

                return(httpResponseMessage);
            }
        }
Пример #22
0
        //https://stackoverflow.com/questions/13260951/how-to-proxy-a-rest-api-with-net-4
        //public async System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> Proxy(Microsoft.AspNetCore.Http.HttpRequest Request)

/*
 *      [HttpHead("{db?}/{id?}/{rev?}")]
 *      [HttpGet("{db?}/{id?}/{rev?}")]
 *      [HttpPost("{db?}/{id?}/{rev?}")]
 *      [HttpPut("{db?}/{id?}/{rev?}")]
 *      [HttpDelete("{db?}/{id?}/{rev?}")]
 */

        public async System.Threading.Tasks.Task <System.Net.Http.HttpResponseMessage> Proxy(Microsoft.AspNetCore.Http.HttpRequest Request)

        {
            System.Net.Http.HttpResponseMessage result = null;

            // Grab the path from /api/*
            var path   = Request.Path.ToString().Replace("/couch", "");
            var target = new UriBuilder("http", "localhost", 5984);
            var method = Request.Method;

            var client = new System.Net.Http.HttpClient();

            client.BaseAddress = target.Uri;

            // Needs to get filled with response.
            string content;

            System.IO.StreamReader reader;
            string jsonInput;

            System.Net.Http.HttpRequestMessage request_message;

            System.Console.WriteLine($"\nmethod:{method} Path: {Request.Path.ToString()} new_path:{path}");
            //System.Net.Http.HttpResponseMessage response;
            switch (method)
            {
            case "POST":
                reader    = new System.IO.StreamReader(Request.Body);
                jsonInput = reader.ReadToEnd();

                // Totally lost here.
                result = await client.PostAsync(path, new System.Net.Http.StringContent(jsonInput, System.Text.Encoding.UTF8, "application/json"));

                break;

            case "PUT":
                reader    = new System.IO.StreamReader(Request.Body);
                jsonInput = reader.ReadToEnd();

                // Totally lost here.
                result = await client.PutAsync(path, new System.Net.Http.StringContent(jsonInput, System.Text.Encoding.UTF8, "application/json"));

                break;

            case "DELETE":
                result = await client.DeleteAsync(path);

                break;

            case "GET":
                // need to capture client data
                //result = await client.GetAsync(path);
                request_message = new System.Net.Http.HttpRequestMessage
                                  (
                    System.Net.Http.HttpMethod.Get,
                    path
                                  );
                result = await client.SendAsync(request_message);

                break;

            case "HEAD":
                request_message = new System.Net.Http.HttpRequestMessage
                                  (
                    System.Net.Http.HttpMethod.Head,
                    path
                                  );
                result = await client.SendAsync(request_message);

                break;

            default:
                System.Console.WriteLine($"\nmethod:{method} Path: {Request.Path.ToString()} new_path:{path} - missing manual.");
                result = await client.GetAsync(path);

                break;
            }

/*
 *          content = await result.Content.ReadAsStringAsync();
 *
 *          foreach (var header in result.Headers)
 *          {
 *              //content.Headers.Add(header.Key, header.Value);
 *              Request.HttpContext.Response.Headers.Add(header.Key, header.Value.ToString());
 *          }
 *          Request.HttpContext.Response.Headers.ContentLength = result.ContentLength;
 */

            //content.Headers.ContentLength = oldContent.Length;
            //response.Content = content;



            //return Content(content, "application/json");
            return(result);
        }
Пример #23
0
        /// <summary>
        /// 
        /// </summary>
        private void startElasticsearchWatcherClient()
        {
            System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient();
            var content = new System.Net.Http.StringContent("{\"trigger\":{\"schedule\":{\"interval\":\"10s\"}},\"input\":{\"search\":{\"request\":{\"body\":{\"query\":{\"term\":{\"alarmType\":{\"value\":\"critical\"}}}}}}},\"condition\":{\"always\":{}},\"actions\":{\"webAction\":{\"webhook\":{\"port\":5000,\"host\":\"localhost\",\"path\":\"/api/WatcherEvents/CriticalAlarm\",\"method\":\"post\",\"headers\":{\"Content-Type\":\"application/json;charset=utf-8\"},\"body\":\"{{ctx.payload.hits.total}}\"}}}}");
            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

            var response = httpClient.PutAsync("http://localhost:9200/_watcher/watch/critical-alarm-watch", content).Result;

        }