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.
Related
I have an ASP.NET Core 6 project using RestSharp (v107.3.0).
Sometimes, I don't how the frequency, luckily it's not often, the library returns a null response and a 0 response status code whatever the API sends.
Here is my code :
private async Task<T> CallApi<T>(myConfig config,
string suffixUrl,
Method method,
HttpStatusCode[] expectedResponses,
string bodyParameter = null)
{
Uri requestUrl = null;
string responseContent = null;
try
{
using (var client = new RestClient(_restClientOptions))
{
var request = new RestRequest(suffixUrl, method);
request.Timeout = 15000;
request.AddHeader("authorization", $"Basic {config.Auth}");
request.AddHeader("content-type", "application/json");
if (bodyParameter != null)
{
request.AddStringBody(bodyParameter, DataFormat.Json);
}
requestUrl = client.BuildUri(request);
var response = await client.ExecuteAsync(request);
// ->>>>>>> Sometimes response.Content equals null and response.statusCode = 0
responseContent = response.Content;
foreach (var expectedResponse in expectedResponses)
{
if (response.StatusCode == expectedResponse)
{
switch (expectedResponse)
{
default:
Logger.LogInformation("reponse :{0}", responseContent);
var obj = JObject.Parse(responseContent);
return obj.ToObject<T>();
}
}
}
Logger.LogWarning("RĂ©ponse innatendue lors d'un apel a l'api, Url={requestUrl}, BodyParameter={bodyParameter}, StatusCode={statusCode}, Reponse={Content}",
requestUrl, bodyParameter, response.StatusCode, responseContent);
}
}
catch (Exception ex)
{
//catch errors
Logger.LogError(ex, "Erreur lors d'un apel a l'api, url={requestUrl}, BodyParameter={bodyParameter}, responseContent={responseContent}",
requestUrl, bodyParameter, responseContent);
}
return default(T);
}
Does somebody else already have a solution for this problem?
Is there a problem with my code ?
Thanks for your help
I know this will not be the perfect answer for the next readers but in my case, I decided to remove Restsharp library and doing calls with HttpClient.
So I have a WPF application that I want to connect to a RESTful API made with Node.js express server, I have the API on my local pc and the WPF app as well and I want to connect the WPF app to a route in the API called "meals", is there a way to do that?
Yes there is a way to do that
the below code sends a post and a get requests to the API just change the port to whatever port you're running your API on
private static readonly HttpClient client = new HttpClient();
public async void SendPostRequestToAPI(){
// POST REQUEST
try
{
var values = new Dictionary<string, string>
{
{ "thing1", "hello" },
{ "thing2", "world" }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://localhost:port", content);
var responseString = await response.Content.ReadAsStringAsync();
}
catch (Exception ex)
{
Console.WriteLine("Error..... " + ex.StackTrace);
}
// GET REQUEST
try
{
var responseString = await client.GetStringAsync("http://localhost:port");
}
catch (Exception ex)
{
Console.WriteLine("Error..... " + ex.StackTrace);
}
}
don't forget to use the following directive
using System.Net.Http;
I am creating a API consumption tool where I have a issue in which It is giving following error when I try to call API. Please help me with this. I am trying to get CSV file and converted to TXT format with this API.
System.Runtime.CompilerServices.AsyncTaskMethodBuilder1+AsyncStateMachineBox1[System.String,StarRezToolApp.Program+d__2]
public static void GetReportInformation(string file_path_1, string Filename)
{
Utility.Utility.Log("TestFIle Reached");
var report_data = HTTP_GET();
Console.WriteLine(report_data.ToString());
var sb_csv = new StringBuilder();
try
{
if (File.Exists(file_path_1 + Filename))
{
using (StreamWriter apiresponse = File.AppendText(file_path_1 + Filename))
{
apiresponse.Write(report_data.ToString());
apiresponse.WriteLine();
}
}
else
{
using (StreamWriter apiresponse = new StreamWriter(file_path_1 + Filename))
{
apiresponse.Write(report_data.ToString());
apiresponse.WriteLine();
}
}
Utility.Utility.Log("File Created Successfully.");
}
catch (Exception ex)
{
Utility.Utility.Log("Error: Could Not Convert. Original error: " + ex.Message);
}
}
I have been calling the following method for other Information
private static async Task<string> HTTP_GET()
{
var TARGETURL = Properties.Resources.URL + Properties.Resources.Report_Name;
Console.WriteLine("GET: + " + TARGETURL);
Utility.Utility.Log("GET: + " + TARGETURL);
NetworkCredential credentials = new NetworkCredential(Properties.Resources.Username, Properties.Resources.Tocken.ToString());
HttpClientHandler handler = new HttpClientHandler
{
Credentials = credentials
};
// ... Use HttpClient with handlers which has credentials
HttpClient client = new HttpClient(handler);
HttpResponseMessage response = await client.GetAsync(TARGETURL);
HttpContent content = response.Content;
// ... Check Status Code
Utility.Utility.Log("Response StatusCode: " + (int)response.StatusCode);
Console.WriteLine("Response StatusCode: " + (int)response.StatusCode);
// ... Read the string.
string result = await content.ReadAsStringAsync();
// ... Display the result.
if (result != null && result.Length >= 50)
{
Utility.Utility.Log("Response message: Successful");
return result.ToString();
}
else
{
Utility.Utility.Log("Response message: " + response.Content);
return null;
}
}
Thank you Mr. #RuardvanElburg. I got the solution by your help.
My controller method GetReportInformationAsync needs to await for response to get out.
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 am developing a Windows Store App using C# and I am very new at this platform (I have been primarily working on IOS and Android).
I have a simple Async method to download raw data from a remote server. It works ok except that I keep seeing random incomplete reads from the WebResponse class. It is pretty simple method and I cant figure out why it would end prematurely. The remote server is working fine ( ios/web/android fine and are retrieving data) so I am obviously doing something wrong here.
Any help will be great in figuring out this problem.
public async Task<byte[]> doGETRequestAsync(String url)
{
callSuccess = false;
byte[] responseFromServer = null;
try
{
WebRequest request = WebRequest.Create(url);
request.Method = "GET";
WebResponse response = await request.GetResponseAsync();
using (Stream dataStream = response.GetResponseStream())
{
responseFromServer = new byte[response.ContentLength];
int readCount = await dataStream.ReadAsync(responseFromServer, 0, (int)response.ContentLength);
if (readCount != response.ContentLength)
throw new IOException("Premature end of data. Expected: " + response.ContentLength + " received: " + readCount);
}
response.Dispose();
}
catch (HttpRequestException hre)
{
Debug.WriteLine("Exception performing network call : " + hre.ToString());
}
catch (Exception e)
{
Debug.WriteLine("Exception performing network call : " + e.ToString());
}
return responseFromServer;
}
I switched to using HttpClient and HttpClientHandler and it works perfectly. This also supports storing cookies and reusing that on every call.
Here is the code that can handle both GET and POST and return the data as an array of bytes[]. If the response is a utf8 encoded string, then the bytes can be converted to string using System.Text.Encoding.UTF8.GetString(respBytes, 0, respBytes.Length);
Hope it is helpful
class Network
{
static CookieContainer cookieJar = new CookieContainer();
List<KeyValuePair<string, string>> postParameters = new List<KeyValuePair<string, string>>();
// Add post parameter before calling NetworkRequestAsync for POST calls.
public void addPostParameter(String key, String value)
{
postParameters.Add(new KeyValuePair<string, string>(key, value));
}
public async Task<byte[]> NetworkRequestAsync(String url, bool GET_REQUEST)
{
callSuccess = false;
byte[] respBytes = null;
try
{
HttpClientHandler handler = new HttpClientHandler()
{
// Use and reuse cookies in the cookiejar
CookieContainer = cookieJar
};
handler.AllowAutoRedirect = false;
handler.UseCookies = true;
HttpClient client = new HttpClient(handler as HttpMessageHandler)
{
BaseAddress = new Uri(#url)
};
HttpResponseMessage response = null;
if (GET_REQUEST)
{
response = await client.GetAsync(client.BaseAddress);
}
else
{
HttpContent content = new FormUrlEncodedContent(postParameters);
//String postparam=await content.ReadAsStringAsync();
//Debug.WriteLine("Post Param1=" + postparam);
response = await client.PostAsync(client.BaseAddress, content);
callSuccess = true;
}
respBytes = await response.Content.ReadAsByteArrayAsync();
}
catch (Exception e)
{
Debug.WriteLine("Exception performing network call : " + e.ToString());
}
return respBytes;
}
}