public void PutAsXmlAsync_String_WhenUriIsNull_ThrowsException() { Assert.Throws <InvalidOperationException>( () => _client.PutAsXmlAsync((string)null, new object()), "An invalid request URI was provided. The request URI must either be an absolute URI or BaseAddress must be set." ); }
public static void Put <TRequest>(this HttpClient httpClient, string requestUri, TRequest content, DataFormat dataFormat, out HttpResponseMessage httpResponseMessage, out string responseString) where TRequest : class { httpClient.DefaultRequestHeaders.Accept.Clear(); switch (dataFormat) { case DataFormat.Xml: { httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml")); httpResponseMessage = httpClient.PutAsXmlAsync(requestUri, content).Result; responseString = httpResponseMessage.Content.ReadAsStringAsync().Result; } break; default: { httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); httpResponseMessage = httpClient.PutAsJsonAsync(requestUri, content).Result; responseString = httpResponseMessage.Content.ReadAsStringAsync().Result; } break; } }
public async Task <T> PutAsync <P, T>(string relativePath, P submittingData, string mediaType = "application/json") { using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient()) { client.BaseAddress = new Uri(BaseUrl); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(mediaType)); HttpResponseMessage response = null; if (submittingData.GetType() == typeof(FormUrlEncodedContent)) { response = await client.PutAsync(relativePath, ((FormUrlEncodedContent)Convert.ChangeType(submittingData, typeof(FormUrlEncodedContent)))); } else if ((mediaType?.ToLower()).Contains("xml")) { response = await client.PutAsXmlAsync <P>(relativePath, submittingData); } else { response = await client.PutAsJsonAsync <P>(relativePath, submittingData); } response.EnsureSuccessStatusCode(); T result = await response.Content.ReadAsAsync <T>(); return(result); } }
public void PutAsXmlAsync_Uri_WhenClientIsNull_ThrowsException() { HttpClient client = null; Assert.ThrowsArgumentNull( () => client.PutAsXmlAsync(new Uri("http://www.example.com"), new object()), "client" ); }
public void Put_throws_not_implemented_exception() { var config = new HttpSelfHostConfiguration("http://localhost:8080"); config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Never; config.Filters.Add(new NotImplementedErrorFilter()); config.Routes.MapHttpRoute( "DefaultApi", "api/{controller}/{id}", new { id = RouteParameter.Optional }); config.Formatters.Add(new EuricomFormatter()); config.MessageHandlers.Add(new MethodOverrideHandler()); config.DependencyResolver = new DependencyResolver(); var server = new HttpServer(config); var client = new HttpClient(server); var result = client.PutAsXmlAsync<Bank>("http://localhost:8080/api/bank/1", (new Bank() { BIC = "1", Name = "KBC" })).Result; Assert.AreEqual(HttpStatusCode.NotImplemented, result.StatusCode); }
/// <summary> /// Calls API to update order. /// </summary> /// <param name="updatedOrder">Updated order to be saved</param> /// <param name="editEvents">List of id's of edit events to be executed</param> /// <returns>Tuple of bool and string, bool == true when API succeded, bool == false when API did not succeed, string == fail message.</returns> public Tuple<bool, string> PutUpdateOrder(Order updatedOrder, List<int> editEvents) { using (var client = new HttpClient()) { try { var dto = new Tuple<Order, List<int>>(updatedOrder, editEvents); client.BaseAddress = _baseAddress; var response = client.PutAsXmlAsync("api/order/updateorder", dto).Result; if (response.IsSuccessStatusCode) { return new Tuple<bool, string>(true, response.StatusCode.ToString()); } else //do failure thing { return new Tuple<bool, string>(false, "Could not save updated order: Error from Web api: " + response.StatusCode.ToString() + ": " + response.ReasonPhrase); } } catch (Exception ex) { throw; } } }
private async Task <T> UpdateInfoFromWebApi <U>(string path, string id, U model) { var httpClient = new System.Net.Http.HttpClient { BaseAddress = new Uri(baseUri + path + id), Timeout = TimeSpan.FromSeconds(60), }; try { var response = await httpClient.PutAsXmlAsync("", model); response.EnsureSuccessStatusCode(); if (response.IsSuccessStatusCode) { return(response.Content.ReadAsAsync <T>().Result); } } catch (Exception ex) { } return(null); }
/// <summary> /// Sends a PUT request as an asynchronous operation to the specified Uri with the given <paramref name="value"/> serialized /// as XML. /// </summary> /// <remarks> /// This method uses the default instance of <see cref="XmlMediaTypeFormatter"/>. /// </remarks> /// <typeparam name="T">The type of <paramref name="value"/>.</typeparam> /// <param name="client">The client used to make the request.</param> /// <param name="requestUri">The Uri the request is sent to.</param> /// <param name="value">The value that will be placed in the request's entity body.</param> /// <returns>A task object representing the asynchronous operation.</returns> public static Task <HttpResponseMessage> PutAsXmlAsync <T>(this HttpClient client, Uri requestUri, T value) { return(client.PutAsXmlAsync(requestUri, value, CancellationToken.None)); }
public static void UpdateArtist(HttpClient client, int id, string newName = null, string newCountry = null, DateTime? newDateOfBirth = null) { if (id <= 0) { throw new ArgumentOutOfRangeException("Id must be a positive integer."); } HttpResponseMessage response = client.GetAsync("api/Artist/" + id).Result; if (response.IsSuccessStatusCode) { var artist = response.Content.ReadAsAsync<SerializableArtist>().Result; Artist updatedArtist = new Artist(); updatedArtist.ArtistId = id; if (newCountry != null) { updatedArtist.Country = newCountry; } else { updatedArtist.Country = artist.Country; } if (newDateOfBirth != null) { updatedArtist.DateOfBirth = newDateOfBirth.Value; } else { updatedArtist.DateOfBirth = artist.DateOfBirth; } if (newName != null) { updatedArtist.Name = newName; } else { updatedArtist.Name = artist.Name; } HttpResponseMessage innerResponse = null; if (client.DefaultRequestHeaders.Accept.Contains(new MediaTypeWithQualityHeaderValue("application/xml"))) { innerResponse = client.PutAsXmlAsync<Artist>("api/Artist/" + id, updatedArtist).Result; } else if (client.DefaultRequestHeaders.Accept.Contains(new MediaTypeWithQualityHeaderValue("application/json"))) { innerResponse = client.PutAsJsonAsync<Artist>("api/Artist/" + id, updatedArtist).Result; } if (innerResponse == null) { throw new InvalidOperationException("Client must use json or xml."); } if (innerResponse.IsSuccessStatusCode) { Console.WriteLine("Update successful."); } else { Console.WriteLine("{0} ({1})", (int)innerResponse.StatusCode, innerResponse.ReasonPhrase); } } else { Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase); } }
/// <summary> /// Execute event on API /// </summary> /// <param name="eventToExecute">Event to execute</param> /// <returns>Tuple of bool and string, bool == true when API succeded, bool == false when API did not succeed, string == fail message.</returns> public Tuple<bool, string> PutExecuteEvent(Event eventToExecute) { using (var client = new HttpClient()) { client.BaseAddress = _baseAddress; var response = client.PutAsXmlAsync("api/order/executeevent", eventToExecute).Result; if (response.IsSuccessStatusCode) { return new Tuple<bool, string>(true, response.StatusCode.ToString()); } else //do failure thing { return new Tuple<bool, string>(false, "Could not execute event: Error from Web api: " + response.StatusCode.ToString() + ": " + response.ReasonPhrase); } } }
/// <summary> /// Archives order on Web API (Does not delete order on Web API) /// </summary> /// <param name="order">Order to be deleted</param> /// <returns>Tuple of bool and string. bool == true when API succeded, bool == false when API did not succeed, string == fail message.</returns> public Tuple<bool, string> PutDeleteOrder(Order order) { using (var client = new HttpClient()) { try { client.BaseAddress = _baseAddress; var response = client.PutAsXmlAsync("api/order/archive", order).Result; //Archiving, not deleting if (response.IsSuccessStatusCode) { return new Tuple<bool, string>(true, response.StatusCode.ToString()); } else //do failure thing { return new Tuple<bool, string>(false, "Could not delete order: Error from Web api: " + response.StatusCode.ToString() + ": " + response.ReasonPhrase); } } catch (Exception ex) { throw; } } }
internal static void UpdateAlbumAsXML(HttpClient Client, int id, Album album) { var response = Client.PutAsXmlAsync("api/Albums/" + id, album).Result; if (response.IsSuccessStatusCode) { Console.WriteLine("Album updated!"); } else { Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase); } }
internal static void UpdateSongAsXML(HttpClient Client, int id, Song song) { var response = Client.PutAsXmlAsync("api/Songs/" + id, song).Result; if (response.IsSuccessStatusCode) { Console.WriteLine("Song updated!"); } else { Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase); } }
public static void PutArtistXml(HttpClient client) { client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml")); Console.WriteLine("Enter artist id"); string id = Console.ReadLine(); Console.WriteLine("Enter artist name"); string name = Console.ReadLine(); Console.WriteLine("Enter artist country"); string country = Console.ReadLine(); Console.WriteLine("Enter artist birth date"); DateTime birthDate = DateTime.ParseExact(Console.ReadLine(), "dd.MM.yyyy", new CultureInfo("en-US")); Artist artist = new Artist { Name = name, Country = country, DateOfBirth = birthDate }; HttpResponseMessage response = client.PutAsXmlAsync(string.Format("api/artists/{0}", id), artist).Result; if (response.IsSuccessStatusCode) { Console.WriteLine("Artist changed"); } else { Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase); } }
public static void PutAlbumXml(HttpClient client) { client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml")); Console.WriteLine("Enter album id"); string albumId = Console.ReadLine(); Console.WriteLine("Enter album title"); string title = Console.ReadLine(); Console.WriteLine("Enter album year"); int year = int.Parse(Console.ReadLine()); Console.WriteLine("Enter producer"); string producer = Console.ReadLine(); Album album = new Album { AlbumTitle = title, AlbumYear = year, Producer = producer }; HttpResponseMessage response = client.PutAsXmlAsync(string.Format("api/songs/{0}", albumId), album).Result; if (response.IsSuccessStatusCode) { Console.WriteLine("Album changed"); } else { Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase); } }
public static void UpdateAlbum(HttpClient client, int id, string newTitle = null, string newProducer = null, int? newYear = null) { if (id <= 0) { throw new ArgumentOutOfRangeException("Id must be a positive integer."); } HttpResponseMessage response = client.GetAsync("api/Album/" + id).Result; if (response.IsSuccessStatusCode) { var album = response.Content.ReadAsAsync<SerializableAlbum>().Result; Album updatedAlbum = new Album(); updatedAlbum.AlbumId = id; if (newTitle != null) { updatedAlbum.Title = newTitle; } else { updatedAlbum.Title = album.Title; } if (newProducer != null) { updatedAlbum.Producer = newProducer; } else { updatedAlbum.Producer = album.Producer; } if (newYear != null) { updatedAlbum.Year = newYear.Value; } else { updatedAlbum.Year = album.Year; } HttpResponseMessage innerResponse = null; if (client.DefaultRequestHeaders.Accept.Contains(new MediaTypeWithQualityHeaderValue("application/xml"))) { innerResponse = client.PutAsXmlAsync<Album>("api/Album/" + id, updatedAlbum).Result; } else if (client.DefaultRequestHeaders.Accept.Contains(new MediaTypeWithQualityHeaderValue("application/json"))) { innerResponse = client.PutAsJsonAsync<Album>("api/Album/" + id, updatedAlbum).Result; } if (innerResponse == null) { throw new InvalidOperationException("Client must use json or xml."); } if (innerResponse.IsSuccessStatusCode) { Console.WriteLine("Update successful."); } else { Console.WriteLine("{0} ({1})", (int)innerResponse.StatusCode, innerResponse.ReasonPhrase); } } else { Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase); } }
public static void PutSongXml(HttpClient client) { client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml")); Console.WriteLine("Enter song id"); string songId = Console.ReadLine(); Console.WriteLine("Enter song title"); string title = Console.ReadLine(); Console.WriteLine("Enter song year"); int year = int.Parse(Console.ReadLine()); Console.WriteLine("Enter song genre code"); Genre genre = (Genre)int.Parse(Console.ReadLine()); Console.WriteLine("Enter song description"); string description = Console.ReadLine(); Console.WriteLine("Enter song artist id"); int id = int.Parse(Console.ReadLine()); Song song = new Song { SongTitle = title, SongYear = year, SongGenre = genre, Description = description, ArtistId = id }; HttpResponseMessage response = client.PutAsXmlAsync(string.Format("api/songs/{0}", songId), song).Result; if (response.IsSuccessStatusCode) { Console.WriteLine("Song changed"); } else { Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase); } }
public static void UpdateSong(HttpClient client, int id, Artist song) { HttpResponseMessage response; if (client.DefaultRequestHeaders.Accept.Contains(new MediaTypeWithQualityHeaderValue("application/json"))) { response = client.PutAsJsonAsync("api/songs/" + id, song).Result; } else { response = client.PutAsXmlAsync("api/songs/" + id, song).Result; } if (response.IsSuccessStatusCode) { Console.WriteLine("Song {0} updated successfully", song.Name); } else { Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase); } }