async void ButtonDeleteRestToDo_Click(object sender, RoutedEventArgs e)
        {
            var button = (Button)sender;

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

            try
            {
                ToDoItem todo = ((ToDoItem)button.DataContext);
#if !OPENSILVER
                var    webClient = new WebClient();
                string response  = await webClient.UploadStringTaskAsync("http://cshtml5-rest-sample.azurewebsites.net/api/Todo/" + todo.Id.ToString() + "?OwnerId=" + _ownerId.ToString(), "DELETE", "");
#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.DeleteAsync("http://cshtml5-rest-sample.azurewebsites.net/api/Todo/" + todo.Id.ToString() + "?OwnerId=" + _ownerId.ToString());
#endif

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

            button.IsEnabled = true;
            button.Content   = "Delete";
        }
Ejemplo n.º 2
0
        public IActionResult Delete(Guid id)
        {
            System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
            client.BaseAddress = new Uri(_configuration.GetValue <string>("AppConfig:Url"));
            var result = client.DeleteAsync("/api/StudentService/" + id).Result;

            return(RedirectToAction("Index"));
        }
Ejemplo n.º 3
0
        public async Task DeleteAsync(int id)
        {
            var client   = new System.Net.Http.HttpClient();
            var address  = $"http://mrropke-001-site1.gtempurl.com/api/retters/{id}";
            var uri      = new Uri(string.Format(address, id));
            var response = await client.DeleteAsync(uri);

            if (response.IsSuccessStatusCode)
            {
                await DisplayAlert("Deleted", "The recipe is deleted", "OK");
            }
        }
Ejemplo n.º 4
0
        public async Task <IActionResult> OnPostAsync(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            if (Bug != null)
            {
                using (var client = new System.Net.Http.HttpClient())
                {
                    var requestUri = new Uri("http://bugtrackerbackend/api/bug/" + id);
                    var response   = await client.DeleteAsync(requestUri);
                }
            }

            return(RedirectToPage("./Index"));
        }
        public static async void DeleteAccountAsync(string accountNumber)
        {
            try
            {
                var client = new System.Net.Http.HttpClient();
                client.DefaultRequestHeaders.Add("Accept", "application/json");
                client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", App.Token);
                var address = $"{App.ApiBaseURL}/api/Accounts/{accountNumber}";

                var response = await client.DeleteAsync(address);

                if (response.IsSuccessStatusCode)
                {
                    //TODO
                }
            }
            catch (Exception ee)
            {
                //TODO
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// 將 DELETE 要求傳送至指定的 URI
        /// </summary>
        /// <param name="uri">The RequestUri</param>
        public void Delete(Uri uri)
        {
            if (uri == null)
            {
                throw new ArgumentNullException("uri");
            }

            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.DeleteAsync(uri).Result;

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

                this.HttpStatusCode = response.StatusCode;
            }
        }
Ejemplo n.º 7
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);
            }
        }
Ejemplo n.º 8
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();
        }
Ejemplo n.º 9
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);
        }
Ejemplo n.º 10
0
 public async void DeleteWatcher()
 {
     System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient();
     var response = await httpClient.DeleteAsync("http://localhost:9200/_watcher/watch/critical-alarm-watch");
 }
Ejemplo n.º 11
0
 public async void DeleteWatcher()
 {
     System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient();
     var response = await httpClient.DeleteAsync("http://localhost:9200/_watcher/watch/critical-alarm-watch");
 }
Ejemplo n.º 12
0
 public async Task DeleteAsync(string requestUri)
 {
     await httpClient.DeleteAsync(requestUri);
 }