The following code successfully gets data from a web service and displays it in a Windows 8 desktop app.
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("http://localhost:12345/api/items");
var info = new List<SampleDataGroup>();
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
var item = JsonConvert.DeserializeObject<dynamic>(content);
foreach (var data in item)
{
var infoSect = new SampleDataGroup
(
(string)data.Id.ToString(),
(string)data.Name,
(string)"",
(string)data.PhotoUrl,
(string)data.Description
);
info.Add(infoSect);
}
}
else
{
MessageDialog dlg = new MessageDialog("Error");
await dlg.ShowAsync();
}
This does however require an internet connection to work. The app crashes every time there is no internet connection.
How do I write a try catch statement in this code to display a pop up message if the network connection doesnt work?
EDIT:
I am trying to use MessageDialog below, and this stops the app from crashing, but it doesn't bring up the message.
catch (Exception ex)
{
MessageDialog err = new MessageDialog(ex.Message);
}
Don't you need
string errorMessage = string.Empty;
try
{
HttpClient client = new HttpClient();
HttpResponseMessage response = await
client.GetAsync("http://localhost:12345/api/items");
var info = new List<SampleDataGroup>();
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
var item = JsonConvert.DeserializeObject<dynamic>(content);
foreach (var data in item)
{
var infoSect = new SampleDataGroup
(
(string)data.Id.ToString(),
(string)data.Name,
(string)"",
(string)data.PhotoUrl,
(string)data.Description
);
info.Add(infoSect);
}
}
else
{
errorMessage = "Error";
}
}
catch (Exception ex)
{
ErrorMessage = ex.Message;
}
if (errorMessage != string.Empty)
{
MessageDialog dlg = new MessageDialog(errorMessage);
await dlg.ShowAsync();
}
?
Related
I am trying to call simple POST API to create a Zendesk Ticket from Console App.
I create C# core console app in VS2019 and pasted simple code which should create New Ticket.
code work in other app but in console app, app just log out from debug...
call never goes...
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://testhelp.zendesk.com/api/v2/tickets.json"))
{
try
{
var base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes("test#test.com:testPassword"));
request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}");
request.Content = new StringContent("{\"ticket\": {\"subject\": \"My first Ticket!\", \"comment\": { \"body\": \"The ticket is from API.\" }}}");
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
HttpResponseMessage response = await httpClient.SendAsync(request).ConfigureAwait(false);
string content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
Console.WriteLine(response);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
What am I missing?
Async calls are frigid mistresses in some cases.
A good option is to make your main program async and therefore able to await tasks. The issue here is with GUI if that is what you actually have when you get away from the command line I am not sure how well it plays with UI threads, but here is the example. Which is much more elegant.
static async Task Main(string[] args)
{
var TicketTask = await createTicket();
}
async static Task<string> createTicket()
{
var content = "unknown error";
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://testhelp.zendesk.com/api/v2/tickets.json"))
{
try
{
var base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes("test#test.com:testPassword"));
request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}");
request.Content = new StringContent("{\"ticket\": {\"subject\": \"My first Ticket!\", \"comment\": { \"body\": \"The ticket is from API.\" }}}");
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
HttpResponseMessage response = await httpClient.SendAsync(request).ConfigureAwait(false);
content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
//Console.WriteLine(response);
}
catch (Exception ex)
{
content = ex.Message;
}
}
}
return content;
}
Quick-and-dirty-simple-solution (which I would not suggest for production) is to monitor content within the main loop as a global variable where you fill it on success or failure.
static string content = "";
static void Main(string[] args)
{
var loopcount = 0;
var t = new Task(createTicket);
t.Start();
while(content == "" && loopcount < 50000)
{
System.Threading.Thread.Sleep(100);
loopcount++;
}
}
async static void createTicket()
{
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://testhelp.zendesk.com/api/v2/tickets.json"))
{
try
{
var base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes("test#test.com:testPassword"));
request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}");
request.Content = new StringContent("{\"ticket\": {\"subject\": \"My first Ticket!\", \"comment\": { \"body\": \"The ticket is from API.\" }}}");
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
HttpResponseMessage response = await httpClient.SendAsync(request).ConfigureAwait(false);
content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
//Console.WriteLine(response);
}
catch (Exception ex)
{
content = ex.mesage;
}
}
}
}
Is it possible to open a link in browser with HttpClient.GetAsync?
I got a report from a user of my app that the app opened a link in the browser which is only used in with HttpClient.GetAsync.
Some one else had the issue too: why HttpClient.GetAsync causes opening link in browser?
private JObject Get(string url)
{
JObject getResponse = new JObject();
getResponse["error"] = (int)Error.None;
getResponse["message"] = "";
try
{
using (HttpClient client = new HttpClient())
{
Task<HttpResponseMessage> res1 = client.GetAsync(url + GetRequestRandomizer());
HttpResponseMessage res = res1.WaitAndUnwrapException();
if (res.IsSuccessStatusCode && res.StatusCode == HttpStatusCode.OK)
{
var responseContent = res.Content;
getResponse["error"] = (int)Error.None;
getResponse["message"] = responseContent.ReadAsStringAsync().Result;
}
else
{
getResponse["error"] = (int)Error.RequestError;
getResponse["message"] = "";
}
}
}
catch (HttpRequestException exception)
{
getResponse["error"] = (int)Error.NetworkError;
getResponse["message"] = "";
}
return getResponse;
}
I wrote simple method for getting data from (online) REST Service:
public async Task<Object> GetTask()
{
try
{
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri("http://111.111.111.111:8080/");
HttpResponseMessage result = await client.GetAsync("ABC/CDE/getsomeinfo");
if (result.IsSuccessStatusCode)
{
//Deserialize
}
}
}
catch (Exception ex)
{
Debug.WriteLine("Error" + ex);
}
return null;
}
Whenever i run this on UWP i'm getting catch exception:
The text associated with this error code could not be found.
A connection with the server could not be established
HResult 2147012867
Im trying to connect my client with restapi in internal network. In forms same code is working properly.
Try this
HttpResponseMessage response;
public async Task<string> webserviceResponse(string HttpMethod)
{
// check internet connection is available or not
if (NetworkInterface.GetIsNetworkAvailable() == true)
{
// CancellationTokenSource cts = new CancellationTokenSource(2000); // 2 seconds
HttpClient client = new HttpClient();
MultipartFormDataContent mfdc = new MultipartFormDataContent();
mfdc.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");
string GenrateUrl = "your url";
if (HttpMethod == "POST")
{
response = await client.PostAsync(GenrateUrl, mfdc);
}
else if (HttpMethod == "PUT")
{
response = await client.PutAsync(GenrateUrl, mfdc);
}
else if (HttpMethod == "GET")
{
response = await client.GetAsync(GenrateUrl);
}
var respon = await response.Content.ReadAsStringAsync();
string convert_response = respon.ToString();
return convert_response;
}
else
{
return "0";
}
}
I'm developing a windows phone app that generates a QRcode, when the code is scanned, then response has to come back as true, please look at my code and advice as i'm getting a false response even thought the other app has scanned the code.
private async void queryQRCode(string code)
{
try
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var authorisationHeader = GenerateBasicAuthorizationParameter("merchant-" + ObjUserData.MerchantId, ObjUserData.PassApiPassword); // 12ED5A5F2B38ACCBE437731BB2AC1F30 35A09A5C2AE97F055A0FDAEDA5A7093D
//Console.WriteLine ("http content - " + httpContent.ReadAsStringAsync().Result);
HttpResponseMessage httpResponse = new HttpResponseMessage();
// Do the actual request and await the response
client.DefaultRequestHeaders.Authorization = authorisationHeader;
var f = QueryCodeUrl + "/" + code + "/scanned";
httpResponse = await client.GetAsync(new Uri(f));
//httpResponse.EnsureSuccessStatusCode();
// If the response contains content we want to read it!
if (httpResponse.Content != null)
{
var responseContent = await httpResponse.Content.ReadAsStringAsync();
// From here on you could deserialize the ResponseContent back again to a concrete C# type using Json.Net
Debug.WriteLine(responseContent);
try
{
ScannedCodeResult res = JsonConvert.DeserializeObject<ScannedCodeResult>(responseContent);
Debug.WriteLine("RETURNED RESPONSE IS "+res.scanned.ToString());
if (res.scanned == false)
{
queryQRCode(code);
}
else
{
Debug.WriteLine("YAY!!!! The User has successfully scanned the application");
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message + ex.StackTrace);
}
// var qrResponse = (VcsMasterPassService.MasterPassModels.QRCodeResponse)JsonConvert.DeserializeObject (responseContent, typeof(VcsMasterPassService.MasterPassModels.QRCodeResponse));
// CreateQRCodeImage (qrResponse.code);
}
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message + ex.StackTrace);
}
finally
{
}
}
Above problem is caused by windows phone caching.
I m developing a Windows Phone 8.1 Application.
I'm newbie in C# and WP. I used restfull web services for sql server connection but i can't send data to server. I had an error message as "Bad Request".
This is my login page code bihend
KullaniciManager km = new KullaniciManager();
km.Login();
HttpClient httpClient = new System.Net.Http.HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "http://localhost:3577/KullaniciService.svc/Login");
HttpResponseMessage response = await httpClient.SendAsync(request);
MessageDialog msgbox = new MessageDialog("Serverdan gelecek hata mesajı");
await msgbox.ShowAsync();
My BLL code is here.
public LoginResponse KullaniciKontrolEt(string kulAdi, string sifre)
{
LoginResponse response = null;
using (NeydiolilacEntities noi = new NeydiolilacEntities())
{
object data = noi.ta_Kullanici.Where(x => x.Kul_Ad == kulAdi && x.Kul_Sifre == sifre && x.Kul_Statu == true).SingleOrDefault();
response = new LoginResponse()
{
Data = data
};
return response;
}
Thanks for your help :)
*
Hi Asim,
This will help you I hope
Note : Code for Win8.1
public async Task<string> GeneralRequestHandler(string RequestUrl, object ReqObj)
{
try
{
string json = Newtonsoft.Json.JsonConvert.SerializeObject(ReqObj);
HttpContent content = new StringContent(json);
Windows.Web.Http.IHttpContent c = new Windows.Web.Http.HttpStringContent(json);
c.Headers.ContentType = new Windows.Web.Http.Headers.HttpMediaTypeHeaderValue("application/json");
Windows.Web.Http.Filters.HttpBaseProtocolFilter aHBPF = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
aHBPF.IgnorableServerCertificateErrors.Add(Windows.Security.Cryptography.Certificates.ChainValidationResult.Untrusted);
aHBPF.IgnorableServerCertificateErrors.Add(Windows.Security.Cryptography.Certificates.ChainValidationResult.InvalidName);
string responseText;
using (var handler = new Windows.Web.Http.HttpClient(aHBPF))
{
Windows.Web.Http.HttpResponseMessage r = await handler.PostAsync(new Uri(RequestUrl), c);
responseText = await r.Content.ReadAsStringAsync();
}
}
catch (HttpRequestException ex)
{
}
return responseText;
}
*