I have PHP file which gives me following JSON:
{"Name":"Waqas","Age":37,"Address":"Kanju"}
When I execute this method in Windows Phone it gives me the same JSON:
{"Name":"Waqas","Age":37,"Address":"Kanju"}
in textblock named tblock.Text;
This is my method for receiving data from PHP file in JSON format:
public async void sndandrec(string feedingaddress, HttpResponseMessage response, TextBlock tblock, HttpClient myhttpClient)
string responseText;
tblock.Text = "Waiting for response ...";
try
{
response = await myhttpClient.GetAsync(resourceUri);
response.EnsureSuccessStatusCode();
responseText = await response.Content.ReadAsStringAsync();
}
catch (Exception ex)
{
// Need to convert int HResult to hex string
tblock.Text = "Error = " + ex.HResult.ToString("X") +
" Message: " + ex.Message;
responseText = "";
}
tblock.Text = response.StatusCode + " " + response.ReasonPhrase;
tblock.Text = responseText.ToString();
This is my class:
public class RootObject
{
public string Name { get; set; }
public int Age { get; set; }
public int Address { get; set; }
}
I would like to show the Name value in TextboxName, similary Age value in TextboxAge and Address value in TextboxAddress. I don't know how to do that.
Okay, major edit, and I basically removed all of my last answer because of it being incorrect.
Reference a JSON library, the easiest is to search for JSON.NET on NuGet and reference that. Then you can make a call to your server and parse the JSON data.
WebRequest request = WebRequest.Create("http://addresstojson.com/json.json");
WebResponse response = await request.GetResponseAsync();
using(var stream = new StreamReader(response.GetResponseStream()))
{
json = JsonConvert.DeserializeObject<RootObject>(stream.ReadToEnd());
}
Then you can still set the textblocks with the data retrieved using your RootObject class you defined in your question
tbName.Text = "Name: " + json.Name;
tbAge.Text = "Age: " + json.Age;
tbAddress.Text = "Address: " + json.Address;
Here is the JSON I used for this example:
{
"name": "John Doe",
"age": 25,
"Address": "Mars"
}
Related
I'm new to working with async and I'm trying to build a Cefsharp application that collects data from an external API, stores it in local variables and then exports these through JavaScript to HTML. It's not a beautiful implementation and I'm sure my code is pretty awful but here goes:
My application performs a tick every 5 seconds, where it executes a HTTP Post request and stores the result in a QuickType (app.quicktype.io) list. This is the tick:
private async void timer1_Tick(object sender, EventArgs e)
{
await chromeBrowser.WaitForInitialLoadAsync();
if (httpPost.ConnectionSuccesful())
{
var devtoolsContext = await chromeBrowser.CreateDevToolsContextAsync();
var postResult = await httpPost.SendPost("robot_info");
try {
var result = Welcome.FromJson(postResult);
foreach (var robot in result.Result.Robots.Select((value, i) => (value, i)))
{
Console.WriteLine(robot.value.Id);
if (robot.value.ChargingStateCode == 9 || robot.value.ChargingStateCode == 12)
await devtoolsContext.EvaluateFunctionAsync("function setBatteryCharge() { var batteryLevel = jQuery('#robot" + robot.i + "Charge'); batteryLevel.css('width', "+ robot.value.StateOfCharge + " + '%'); batteryLevel.text('Charging'); batteryLevel.addClass('high'); batteryLevel.removeClass('medium'); batteryLevel.removeClass('low'); }");
else if (robot.value.StateOfCharge > 75)
await devtoolsContext.EvaluateFunctionAsync("function setBatteryHigh() { var batteryLevel = jQuery('#robot" + robot.i + "Charge'); batteryLevel.css('width', " + robot.value.StateOfCharge + " + '%'); batteryLevel.text(" + robot.value.StateOfCharge + " + '%'); batteryLevel.addClass('high'); batteryLevel.removeClass('medium'); batteryLevel.removeClass('low'); }");
else if (robot.value.StateOfCharge >= 50)
await devtoolsContext.EvaluateFunctionAsync("function setBatteryMedium() { var batteryLevel = jQuery('#robot" + robot.i + "Charge'); batteryLevel.css('width', " + robot.value.StateOfCharge + " + '%'); batteryLevel.text(" + robot.value.StateOfCharge + " + '%'); batteryLevel.addClass('medium'); batteryLevel.removeClass('high'); batteryLevel.removeClass('low'); }");
else
await devtoolsContext.EvaluateFunctionAsync("function setBatteryLow() { var batteryLevel = jQuery('#robot" + robot.i + "Charge'); batteryLevel.css('width', " + robot.value.StateOfCharge + " + '%'); batteryLevel.text(" + robot.value.StateOfCharge + " + '%'); batteryLevel.addClass('low'); batteryLevel.removeClass('high'); batteryLevel.removeClass('medium'); }");
}
}
catch (ArgumentNullException Nex) {
Console.Write("[Error] - " + Nex.Message);
}
catch (Exception ex)
{
Console.WriteLine("[Error] - " + ex.Message);
}
}
else
Console.WriteLine("[Error] - Check connection or access to API server.");
}
I'm currently trying to update the battery level and it successfully does this for the first tick (the JavaScript works as intended and both the css, classes and text is changed). Then it stops working. I've checked that the correct results are coming in from the HTTP Post and that the data is stored properly in the local variables. The problem seems to occur in the foreach. I've tried to read up about async a bit but I can't seem to find the culprit. After the first execution of the code, something seems to be blocking the iteration of the for each. I'm using Cefsharp.Winforms and Cefsharp.Puppeteer.
Any idea on why this is happening? Also thankful for any pointers or tips on how to improve the code.
EDIT: This is the Console Output
[Query] Sending post request to xxx with method 'robot_info'
[Success] - API Post Request was succesful.
PR1#11
PR1#15
[Query] Sending post request to xxx with method 'robot_info'
[Success] - API Post Request was succesful.
PR1#11
[Query] Sending post request to xxx with method 'robot_info'
[Success] - API Post Request was succesful.
PR1#11
The first iteration goes through fine.
EDIT2: This is the timer
public void InitTimer()
{
timer1 = new Timer();
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 5000;
timer1.Start();
}
EDIT3: Method SendPost
public async Task<string> SendPost(string method)
{
HttpClient httpClient = new HttpClient();
string data = new JavaScriptSerializer().Serialize(new
{
jsonrpc = "2.0",
method = method,
id = Guid.NewGuid().ToString()
});
StringContent content = new StringContent(data, System.Text.Encoding.UTF8, "application/json");
try
{
Console.WriteLine("[Query] Sending post request to " + url.ToString() + " with method '" + method + "'");
HttpResponseMessage response = await httpClient.PostAsync(url, content).ConfigureAwait(false);
string result = await response.Content.ReadAsStringAsync();
if (IsValidJson(result))
{
Console.WriteLine("[Success] - API Post Request was succesful.");
return result;
}
else
return null;
} catch (HttpRequestException hre)
{
Console.WriteLine("[Error]: " + hre);
return null;
}
}
EDIT4: Structure of Welcome
public partial class Welcome
{
[JsonProperty("jsonrpc")]
public string Jsonrpc { get; set; }
[JsonProperty("result")]
public Result Result { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
}
public partial class Result
{
[JsonProperty("timestamp")]
public long Timestamp { get; set; }
[JsonProperty("robots")]
public List<Robot> Robots { get; set; }
}
Robots is a list with a bunch of longs and ints.
I am working on Azure Function (Http Trigger), and came across with this task.
I am trying to display the output of method (ListVendors.Run(logger)) into inside variable (responseMessage) so that the values would be carried into Http post.
public static class Function1
{
[FunctionName("HttpTrigger_1111_1")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
///Calling from other method starts:
ILogger logger = Bootstrap.Logger("Program");
ListVendors.Run(logger);
///Calling from other method ends:
log.LogInformation("C# HTTP trigger function processed a request.");
string name = req.Query["name"];
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
name = name ?? data?.name;
string responseMessage = string.IsNullOrEmpty(name)
? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
: $"Hello, {name}. This HTTP triggered function executed successfully.";
return new OkObjectResult(responseMessage);
}
}
Basically, I am trying to insert the output of:
ListVendors.Run(logger);
Inside "responseMessage".
return new OkObjectResult(responseMessage);
How do I modify the code to do that?
Bottom is code for ListVendors:
public static class ListVendors
{
public static void Run(ILogger logger)
{
OnlineClient client = Bootstrap.Client(logger);
ReadByQuery query = new ReadByQuery()
{
ObjectName = "VENDOR",
PageSize = 2, // Keep the count to just 2 for the example
Fields =
{
"RECORDNO",
"VENDORID",
}
};
logger.LogInformation("Executing query to Intacct API");
Task<OnlineResponse> task = client.Execute(query);
task.Wait();
OnlineResponse response = task.Result;
Result result = response.Results[0];
try
{
dynamic json = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(result.Data));
string jsonString = json.ToString();
logger.LogDebug(
"Query successful - page 1 [ Total count={0}, Data={1} ]",
result.TotalCount,
jsonString
);
Console.WriteLine("Page 1 success! Number of vendor objects found: " + result.TotalCount + ". Number remaining: " + result.NumRemaining);
} catch (NullReferenceException e)
{
logger.LogDebug("No response in Data. {0}", e);
}
LogManager.Flush();
int i = 1;
while (result.NumRemaining > 0 && i <= 3 && !string.IsNullOrEmpty(result.ResultId))
{
i++;
ReadMore more = new ReadMore()
{
ResultId = result.ResultId
};
Task<OnlineResponse> taskMore = client.Execute(more);
taskMore.Wait();
OnlineResponse responseMore = taskMore.Result;
Result resultMore = responseMore.Results[0];
try
{
dynamic resultMoreJson =
JsonConvert.DeserializeObject(JsonConvert.SerializeObject(resultMore.Data));
string resultMoreJsonString = resultMoreJson.ToString();
logger.LogDebug(
"Read More successful - page " + i + " [ Total remaining={0}, Data={1} ]",
resultMore.NumRemaining,
resultMoreJsonString
);
Console.WriteLine("Page " + i + " success! Records remaining: " + resultMore.NumRemaining);
}
catch (NullReferenceException e)
{
logger.LogDebug("No response in Data. {0}", e);
}
finally
{
LogManager.Flush();
}
}
Console.WriteLine("Successfully read " + i + " pages");
}
}
}
How do I place an order for futures? I am getting two errors: "The required timestamp parameter was not sent, was empty / null, or is not well formed." OR "The signature for this request is not valid."
public static async void Order()
{
string base_uri = "https://fapi.binance.com/fapi/v1/order?";
string API_Key = "bSQQlu2k5tf0oSUGZsNGptisIxXLux8wb............................";
string Secret_Key = "gWPKP66geFL0ryijnlU3TTepS61.............................";
string symbol = "XRPUSDT";
string side = "BUY";
string type = "MARKET";
string timeInForce = "GTC";
decimal quantity = 20;
long recvWindow = 5000;
long timestamp = GetServerTime();
string queryString = "symbol=" + symbol + "&side=" + side + "type=" + type + "&timeInForce=" + timeInForce;
string signature = HMACHASH(queryString, Secret_Key);
var Payload = new Credentials
{
Quantity = quantity,
RecvWindow = recvWindow,
Timestamp = timestamp,
Signature = signature
};
var stringPayload = JsonConvert.SerializeObject(Payload);
var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/json");
httpContent.Headers.Add("X-MBX-APIKEY", API_Key);
using (var httpClient = new HttpClient())
{
var httpResponse = await httpClient.PostAsync(base_uri + queryString, httpContent);
if (httpResponse.Content != null)
{
var responseContent = await httpResponse.Content.ReadAsStringAsync();
Console.WriteLine(responseContent);
}
}
}
This is how I get the timestamp
public static long GetServerTime()
{
string str = BinanceResponse("https://fapi.binance.com/fapi/v1/time");
string[] arr = str.Split('\"');
str = arr[2].Trim(':', '}');
return long.Parse(str);
}
Credentials class
internal class Credentials
{
[JsonProperty("quantity")]
public decimal Quantity { get; set; }
[JsonProperty("recvWindow")]
public long RecvWindow { get; set; }
[JsonProperty("timestamp")]
public long Timestamp { get; set; }
[JsonProperty("signature")]
public string Signature { get; set; }
}
After serialization
stringPayload = "{"quantity":20.0,"recvWindow":5000,"timestamp":1625061703897,"signature":"2794e66d4e5b5b6338782e058747a567db523.........................."}"
If I try like this:
string queryString = "symbol=" + symbol + "&side=" + side + "&type=" + type +
"&timeInForce=" + timeInForce + "&quantity=" + quantity + "&recvWindow=" +
recvWindow + "×tamp=" + timestamp;
string signature = HMACHASH(queryString, Secret_Key);
queryString += "&signature=" + signature;
Error: "The signature for this request is not valid."
Resolved!
Thank you guys! I used Fiddler and found out that the "timeInForce" parameter is not needed for a type = "MARKET". All the problems were because of him.
string queryString = "symbol=" + symbol + "&side=" + side + "&type=" + type +
̶"̶&̶t̶i̶m̶e̶I̶n̶F̶o̶r̶c̶e̶=̶"̶ ̶+̶ ̶t̶i̶m̶e̶I̶n̶F̶o̶r̶c̶e̶ + "&quantity=" + quantity + "&recvWindow=" +
recvWindow + "×tamp=" + timestamp;
I highly recommend the Binance Postman collection on GitHub to see how to structure your requests:
Binance Postman Collection
Following this I also recommend the Binance Signature Examples found here: Binance Signature Examples
It looks like your signature is being generated without including all of the parameters of the request.
Binance supports setting your parameters for a post request either in the body or in the URL. Personally I've only used everything in the URL, but the signature has to verify all of the parameters, whereas your queryString variable is being converted into a signature, but other data is being sent in the payload afterwards and is not included in the signature.
The response is in the error report. The Binance API require you to send an timestamp.
So you are probably not sending a correct timestamp or not correctly name it.
You can check your requests with an http sniffer like Fiddler.
It's possible that the API is case sensitive so, timestamp should not be "Timestamp" after the serialization. Check it
EDIT: Can you provide the documentation that you used to create the request ? Because the official binance API is asking for POST parameters only
So I'm trying to test a method which takes a city name and calls the OpenWeatherMap Web API by entering in a fake city name but I have absolutely no idea how to do that as all the examples I have encountered so far have been testing classes instead of methods.
How do I go about passing a fake city name to the method? Also, the method to call the API returns a Task so how would I be able to check the output string?
I am completely new to the realm of testing so any help would be much appreciated. I have also included my method code here.
static void Main()
{
string output;
//Declare variables
string strUserLocation;
//Prompt user for city name
Console.Write("Enter your city name: ");
strUserLocation = Console.ReadLine();
try
{
//Retrieve data from API
Task<string> callTask = Task.Run(() => CallWebAPI(strUserLocation));
callTask.Wait();
//Get the result
output = callTask.Result;
Console.WriteLine(output);
if(output == "Invalid city name. \n")
{
Main();
}
else
{
//Quit application
Console.WriteLine("Press the ENTER key to quit the application.");
Console.ReadLine();
}
}
catch (Exception)
{
Console.WriteLine("Invalid city name. \n");
Main();
}
}//end Main
//Method to call OpenWeatherMap API
static async Task<string> CallWebAPI(string location)
{
using (HttpClient client = new HttpClient())
{
//Set base URI for HTTP requests
client.BaseAddress = new Uri("http://api.openweathermap.org/data/2.5/weather");
//Tells server to send data in JSON format
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
string strLocation = location;
string strKey = "keyplaceholder123";
//Send request and await response from server
HttpResponseMessage response = await client.GetAsync("?q=" + strLocation + "&APPID=" + strKey);
if(response.StatusCode == HttpStatusCode.OK)
{
CurrentWeather weather = response.Content.ReadAsAsync<CurrentWeather>().Result;
//Convert temperature from Kelvin to Fahrenheit
float temp = weather.main.temp * 1.8f - 459.67f;
string strTempFahrenheit = temp.ToString("n0");
//Display output
return "The temperature in " + weather.name + " is " + strTempFahrenheit + "°F. \n";
}
else
{
return "Invalid city name. \n";
}
}//end using
}//end CallWebAPI
Test that I have so far
using System;
using TechnicalExercise;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace TechnicalExercise.Test
{
[TestClass]
public class InputTest
{
[TestMethod]
public void UserInput_EnterFakeCity_ReturnError()
{
//Arrange
string strFakeCity = "Fake Lake City";
string expected = "Invalid city name. \n";
string actual;
//Act - Retrieve data from API
Task<string> callTask = Task.Run(() => CallWebAPI(strFakeCity));
callTask.Wait();
actual = callTask.Result;
//Assert - Checks if the actual result is as expected
Assert.Equals(actual, expected);
}
}
}
Just incase you didnt figure it out yet here is the code!
I would also recommend you to take a look at async await and task because these things can be complicated!
Please notice the Task<string> and the returnsinstead of output =
static async Task<string> CallWebAPI(string location)
{
//string output;
using (HttpClient client = new HttpClient())
{
//Set base URI for HTTP requests
client.BaseAddress = new Uri("http://api.openweathermap.org/data/2.5/weather");
//Tells server to send data in JSON format
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
string strLocation = location;
string strKey = "427hdh9723797rg87";
//Send request and await response from server
HttpResponseMessage response = await client.GetAsync("?q=" + strLocation + "&APPID=" + strKey);
if (response.StatusCode == HttpStatusCode.OK)
{
CurrentWeather weather = response.Content.ReadAsAsync<CurrentWeather>().Result;
//Convert temperature from Kelvin to Fahrenheit
float temp = weather.main.temp * 1.8f - 459.67f;
string strTempFahrenheit = temp.ToString("n0");
//Display output
return "The temperature in " + weather.name + " is " + strTempFahrenheit + "°F. \n";
}
else
{
return "Invalid city name. \n";
//Console.WriteLine(output);
Main();
}
}
}
How to send parameter in REST api in xamarin.forms ?
I have created REST API Project in xamarin using PCL.
When I call Simple REST api using Below code in Xamarin.forms (Portable Class Library) then I have Successfully receive json Response.
using (var cl = new HttpClient())
{
var result = await cl.GetStringAsync("http://192.168.1.100/apps/jara/web/api/user/test");
jsonResponseClass des = JsonConvert.DeserializeObject<jsonResponseClass>(result);
lbl1.Text = des.code + " " + des.status + " " + des.message;
}
public class jsonResponseClass
{
public string code { get; set; }
public string status { get; set; }
public string message { get; set; }
}
Using above code I got a response
{
code: 200,
status: "ok",
message: "hello"
}
REST API response type is JSON and type is POST
Now, I want to call below Login Api using paramater.
http://192.168.1.100/apps/jara/web/api/user/login
Paramater : email_id and Password
this api success response type is....
{
code: 200,
status: "Success",
User: {
userid: 126,
token: "d154s4d54s654df5s4df56s4df564s5df4",
email: "shahbuddin#gmail.com",
mobile_number: "9898989898"
},
message: "Successfully logged in"
}
What can i do ?
Finally i can do this using below code....
using (var cl = new HttpClient())
{
var formcontent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string,string>("email_id","shahbuddin#peerbits.com"),
new KeyValuePair<string, string>("password","shah")
});
var request = await cl.PostAsync("http://192.168.1.100/apps/jara/web/api/user/login", formcontent);
request.EnsureSuccessStatusCode();
var response = await request.Content.ReadAsStringAsync();
jsonResponselogin res = JsonConvert.DeserializeObject<jsonResponselogin>(response);
lbl1.Text = res.code + " " + res.status + " " + res.message;
}
This code helpful for Calling REST API with Parameter
Thank you...