HTTP response is never returned - c#

I am building an app in Xamarin.Android ! which determines my Address using google Maps API when given a latitude and longitude. However my App fails to deliver an HTTP response. I don't receive any runtime errors and VS debugger behaves as if my App has hanged.
1> I don't know whether this is an issue of Xamarin.Android
2> As i read somehwere it could be an issue of blocking,asynchronous codes but then I use the same piece of code for my Windows App and it never gave me trouble
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
namespace App_Code
{
public class myLocationProxy
{
public static async Task<RootObject_AutoLocationAddress> getmyLocation(string lat, string lng)
{
var http = new HttpClient();
/*CODE STOPS HERE*/var response = await http.GetAsync(String.Format("http://maps.google.com/maps/api/geocode/json?latlng={0},{1}&sensor=false", Uri.EscapeDataString(lat), Uri.EscapeDataString(lng)));
var result = await response.Content.ReadAsStringAsync();
var serializer = new DataContractJsonSerializer(typeof(RootObject_AutoLocationAddress));
var ms = new MemoryStream(Encoding.UTF8.GetBytes(result));
var data = (RootObject_AutoLocationAddress)serializer.ReadObject(ms);
return data;
}
}
[DataContract]
public class AddressComponent_AutoLocationAddress
{
[DataMember]
public string long_name { get; set; }
[DataMember]
public List<string> types { get; set; }
}
[DataContract]
public class Result_AutoLocationAddress
{
[DataMember]
public List<AddressComponent_AutoLocationAddress> address_components { get; set; }
[DataMember]
public string formatted_address { get; set; }
}
[DataContract]
public class RootObject_AutoLocationAddress
{
[DataMember]
public List<Result_AutoLocationAddress> results { get; set; }
[DataMember]
public string status { get; set; }
}
}

Try below code snippet just added TimeOut value.
public static async Task<RootObject_AutoLocationAddress> getmyLocation(string lat, string lng)
{
var client = new HttpClient()
{
Timeout = TimeSpan.FromMilliseconds(10000) //10 second, This line might help you
};
var response = await client.GetAsync(String.Format("http://maps.google.com/maps/api/geocode/json?latlng={0},{1}&sensor=false", Uri.EscapeDataString(lat), Uri.EscapeDataString(lng)));
var result = await response.Content.ReadAsStringAsync();
var serializer = new DataContractJsonSerializer(typeof(RootObject_AutoLocationAddress));
var ms = new MemoryStream(Encoding.UTF8.GetBytes(result));
var data = (RootObject_AutoLocationAddress)serializer.ReadObject(ms);
return data;
}
Cheers!!

Related

Microsoft Azure Text Translator - Subscription Key Not Working

I am trying to build a basic text translator in console using Microsoft Azure's Text Translator. However, my subscription keys are simply not working. I have generated them multiple times, as well as inputted them manually. Please assist. I have left in the keys for further clarification. Thank you for reading, and for your help.
The code generates this error:
if (null == subscriptionKey)
{
throw new Exception("Please set/export the environment variable: " + key_var);
// This sample requires C# 7.1 or later for async/await.
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
// Install Newtonsoft.Json with NuGet
using Newtonsoft.Json;
namespace TranslateTextSample
{
/// <summary>
/// The C# classes that represents the JSON returned by the Translator Text API.
/// </summary>
public class TranslationResult
{
public DetectedLanguage DetectedLanguage { get; set; }
public TextResult SourceText { get; set; }
public Translation[] Translations { get; set; }
}
public class DetectedLanguage
{
public string Language { get; set; }
public float Score { get; set; }
}
public class TextResult
{
public string Text { get; set; }
public string Script { get; set; }
}
public class Translation
{
public string Text { get; set; }
public TextResult Transliteration { get; set; }
public string To { get; set; }
public Alignment Alignment { get; set; }
public SentenceLength SentLen { get; set; }
}
public class Alignment
{
public string Proj { get; set; }
}
public class SentenceLength
{
public int[] SrcSentLen { get; set; }
public int[] TransSentLen { get; set; }
}
class Program
{
private const string key_var="b1f43a68dce24b0280360691ad68bc75";
private static readonly string subscriptionKey = Environment.GetEnvironmentVariable(key_var);
private const string endpoint_var = "https://consoletexttranslator.cognitiveservices.azure.com/sts/v1.0/issuetoken";
private static readonly string endpoint = Environment.GetEnvironmentVariable(endpoint_var);
static Program()
{
if (null == subscriptionKey)
{
throw new Exception("Please set/export the environment variable: " + key_var);
}
if (null == endpoint)
{
throw new Exception("Please set/export the environment variable: " + endpoint_var);
}
}
// Async call to the Translator Text API
static public async Task TranslateTextRequest(string subscriptionKey, string endpoint, string route, string inputText)
{
object[] body = new object[] { new { Text = inputText } };
var requestBody = JsonConvert.SerializeObject(body);
using (var client = new HttpClient())
using (var request = new HttpRequestMessage())
{
// Build the request.
request.Method = HttpMethod.Post;
request.RequestUri = new Uri(endpoint + route);
request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
// Send the request and get response.
HttpResponseMessage response = await client.SendAsync(request).ConfigureAwait(false);
// Read response as a string.
string result = await response.Content.ReadAsStringAsync();
TranslationResult[] deserializedOutput = JsonConvert.DeserializeObject<TranslationResult[]>(result);
// Iterate over the deserialized results.
foreach (TranslationResult o in deserializedOutput)
{
// Print the detected input languge and confidence score.
Console.WriteLine("Detected input language: {0}\nConfidence score: {1}\n", o.DetectedLanguage.Language, o.DetectedLanguage.Score);
// Iterate over the results and print each translation.
foreach (Translation t in o.Translations)
{
Console.WriteLine("Translated to {0}: {1}", t.To, t.Text);
}
}
}
}
static async Task Main(string[] args)
{
// This is our main function.
// Output languages are defined in the route.
// For a complete list of options, see API reference.
// https://learn.microsoft.com/azure/cognitive-services/translator/reference/v3-0-translate
string route = "/translate?api-version=3.0&to=de&to=it&to=ja&to=th";
// Prompts you for text to translate. If you'd prefer, you can
// provide a string as textToTranslate.
Console.Write("Type the phrase you'd like to translate? ");
string textToTranslate = "Hello, Tommy.";
await TranslateTextRequest(subscriptionKey, endpoint, route, textToTranslate);
Console.WriteLine("Press any key to continue.");
Console.ReadKey();
}
}
}
pls try the code below , it works for me :
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
// Install Newtonsoft.Json with NuGet
using Newtonsoft.Json;
namespace TranslateTextSample
{
/// <summary>
/// The C# classes that represents the JSON returned by the Translator Text API.
/// </summary>
public class TranslationResult
{
public DetectedLanguage DetectedLanguage { get; set; }
public TextResult SourceText { get; set; }
public Translation[] Translations { get; set; }
}
public class DetectedLanguage
{
public string Language { get; set; }
public float Score { get; set; }
}
public class TextResult
{
public string Text { get; set; }
public string Script { get; set; }
}
public class Translation
{
public string Text { get; set; }
public TextResult Transliteration { get; set; }
public string To { get; set; }
public Alignment Alignment { get; set; }
public SentenceLength SentLen { get; set; }
}
public class Alignment
{
public string Proj { get; set; }
}
public class SentenceLength
{
public int[] SrcSentLen { get; set; }
public int[] TransSentLen { get; set; }
}
class Program
{
private const string subscriptionKey = "<your translator API key>";
private const string endpoint = "https://api.cognitive.microsofttranslator.com";
static Program()
{
if (null == subscriptionKey)
{
throw new Exception("Please set/export the environment variable: " + subscriptionKey);
}
if (null == endpoint)
{
throw new Exception("Please set/export the environment variable: " + endpoint);
}
}
// Async call to the Translator Text API
static public async Task TranslateTextRequest(string subscriptionKey, string endpoint, string route, string inputText)
{
object[] body = new object[] { new { Text = inputText } };
var requestBody = JsonConvert.SerializeObject(body);
using (var client = new HttpClient())
using (var request = new HttpRequestMessage())
{
// Build the request.
request.Method = HttpMethod.Post;
request.RequestUri = new Uri(endpoint + route);
request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
// Send the request and get response.
HttpResponseMessage response = await client.SendAsync(request).ConfigureAwait(false);
// Read response as a string.
string result = await response.Content.ReadAsStringAsync();
TranslationResult[] deserializedOutput = JsonConvert.DeserializeObject<TranslationResult[]>(result);
// Iterate over the deserialized results.
foreach (TranslationResult o in deserializedOutput)
{
// Print the detected input languge and confidence score.
Console.WriteLine("Detected input language: {0}\nConfidence score: {1}\n", o.DetectedLanguage.Language, o.DetectedLanguage.Score);
// Iterate over the results and print each translation.
foreach (Translation t in o.Translations)
{
Console.WriteLine("Translated to {0}: {1}", t.To, t.Text);
}
}
}
}
static void Main(string[] args)
{
MainAsync(args).GetAwaiter().GetResult();
Console.ReadKey();
Console.WriteLine("press anykey to exit");
}
static async Task MainAsync(string[] args)
{
string route = "/translate?api-version=3.0&to=de&to=it&to=ja&to=th";
// Prompts you for text to translate. If you'd prefer, you can
// provide a string as textToTranslate.
string textToTranslate = "Hello, Tommy.";
await TranslateTextRequest(subscriptionKey, endpoint, route, textToTranslate);
}
}
}
before you run this console app, pls replace the value of "subscriptionKey" with your own key value here :
Result :
If there is anything unclear , pls feel free to let me know : )

Error when deserializing JSON object "Unexpected character encountered while parsing value: <. Path '', line 0, position 0."

I am trying to stream a large JSON file and deserialize item by item during the streaming.
I am using for this test https://github.com/ysharplanguage/FastJsonParser/blob/master/JsonTest/TestData/fathers.json.txt.
This is my code:
using Newtonsoft.Json;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Newtonsoft.Json.Linq;
using System.Threading.Tasks;
namespace AMServices.Controllers
{
public class FathersData
{
public Father[] fathers { get; set; }
}
public class Someone
{
public string name { get; set; }
}
public class Father : Someone
{
public int id { get; set; }
public bool married { get; set; }
// Lists...
public List<Son> sons { get; set; }
// ... or arrays for collections, that's fine:
public Daughter[] daughters { get; set; }
}
public class Child : Someone
{
public int age { get; set; }
}
public class Son : Child
{
}
public class Daughter : Child
{
public string maidenName { get; set; }
}
public class StreamerController : ApiController
{
static readonly JsonSerializer _serializer = new JsonSerializer();
static readonly HttpClient _client = new HttpClient();
[HttpPost]
[Route("streamer/stream")]
public async Task<IHttpActionResult> stream()
{
string apiUrl = "https://github.com/ysharplanguage/FastJsonParser/blob/master/JsonTest/TestData/fathers.json.txt";
using (var stream = await _client.GetStreamAsync(apiUrl).ConfigureAwait(false))
using (var reader = new StreamReader(stream))
using (var json = new JsonTextReader(reader))
{
if (json == null)
StatusCode(HttpStatusCode.InternalServerError);
JsonSerializer serializer = new JsonSerializer();
JObject obj = JObject.Load(json);
// Father f = serializer.Deserialize<Father>(json);
}
return StatusCode(HttpStatusCode.OK);
}
}
}
When i call this WebAPI Controller Method from Postman i get the following error
"ExceptionMessage": "Unexpected character encountered while parsing value: <. Path '', line 0, position 0.",
"ExceptionType": "Newtonsoft.Json.JsonReaderException",
What is wrong with this code?
You are trying to parse an html page.
Try with the raw version :
https://raw.githubusercontent.com/ysharplanguage/FastJsonParser/master/JsonTest/TestData/fathers.json.txt

How to deserialize XML returned from REST API call?

I am stuck deserializing the returned XML from a RESTful API call.
This is the error message I am getting back:
System.AggregateException : One or more errors occurred. ---->
System.Runtime.Serialization.SerializationException : Error in line 1
position 106. Expecting element 'ArrayOfAPIUtility.PartInfo' from
namespace
'http://schemas.datacontract.org/2004/07/MyProject.Web'..
Encountered 'Element' with name 'Part', namespace ''.
I followed this stackoverflow answer to create a successful REST connection.
The returned XML looks like this:
<Part>
<ItemId>12345</ItemId>
<ItemDescription>Item Description</ItemDescription>
<Cost>190.59</Cost>
<Weight>0.5</Weight>
</Part>
I am trying to to deserialize it like this:
public class PartInfo
{
public string ItemId { get; set; }
public string ItemDescription { get; set; }
public string Cost { get; set; }
public string Weight { get; set; }
}
public void GetPartInfo(string itemId)
{
var URL = ...some URL...;
client.BaseAddress = new Uri(URL);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
HttpResponseMessage response = client.GetAsync(urlParameters).Result;
if (response.IsSuccessStatusCode)
{
var dataObjects = response.Content.ReadAsAsync<IEnumerable<PartInfo>>().Result;
foreach (var d in dataObjects)
{
Console.WriteLine("{0}", d.ItemId);
}
}
}
The result is the error message pasted above.
I think I am missing something very elementary here :-)
Thank you very much for your help!
Try xml linq
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication48
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME); //use parse instead if input is a string
PartInfo partInfo = doc.Elements("Part").Select(x => new PartInfo()
{
ItemId = (string)x.Element("ItemId"),
ItemDescription = (string)x.Element("ItemDescription"),
Cost = (decimal)x.Element("Cost"),
Weight = (double)x.Element("Weight")
}).FirstOrDefault();
}
}
public class PartInfo
{
public string ItemId { get; set; }
public string ItemDescription { get; set; }
public decimal Cost { get; set; }
public double Weight { get; set; }
}
}

Error filling an object array from JSON data using DataContractJsonSerializer

I have one problem. I want to read JSON data from my local link and put it in an object class. My problem is that the object[] did not fill with data. Here is my code:
This is the serverdata.cs file with my object inside that I want to fill:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace Διαχείριση
{
class serverdata
{
public προμηθευτέςRow[] Rows;
[DataContract(Name = "ΠρομηθευτέςResult")]
public struct προμηθευτέςRow
{
[DataMember(Name = "Κωδικός")]
public int Κωδικός { get; set; }
[DataMember(Name = "Όνομα")]
public string Όνομα { get; set; }
[DataMember(Name = "Επίθετο")]
public string Επίθετο { get; set; }
[DataMember(Name = "Τηλέφωνο")]
public string Τηλέφωνο { get; set; }
[DataMember(Name = "Διεύθυνση")]
public string Διεύθυνση { get; set; }
[DataMember(Name = "Mail")]
public string Mail { get; set; }
[DataMember(Name = "Προϊόντα")]
public string[] Προϊόντα { get; set; }
}
}
}
Then I have the Form.cs that I want to read the JSON data from my local server:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.Serialization.Json;
namespace Διαχείριση
{
public partial class Administator_Form : Form
{
serverdata ServerData;
public Administator_Form()
{
ServerData = new serverdata();
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
WebRequest request = WebRequest.Create(string.Format("mylocallink"));
WebResponse response = request.GetResponse();
Stream stream = request.GetResponse().GetResponseStream();
StreamReader sread = new StreamReader(stream);
//string sLine = sread.ReadLine();
//MessageBox.Show(sLine);
DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(List<serverdata.προμηθευτέςRow>));
var result = (List<serverdata.προμηθευτέςRow>)json.ReadObject(stream);
ServerData.Rows = result.ToArray();
}
}
}
Now if I call for example MessageBox.Show(ServerData.Rows[0].Κωδικός.ToString()); I get an exception:
"An unhandled exception of type 'System.IndexOutOfRangeException' occurred in Project.exe
Additional information: Index was outside the bounds of the array."
So my problem is that result didn't fill ServerData.Rows.
Here is the JSON data:
{
"ΠρομηθευτέςResult": [
{
"Mail": "mail1",
"Όνομα": "name1",
"Διεύθυνση": "address1",
"Επ‌​ίθετο": "epitheto1",
"Κωδικός": 1,
"Προϊόντα": [
"subproduct1.1",
"subproduct1.2"
],
"Τηλέ‌​φωνο": "1111111111"
},
{
"Mail": "mail2",
"Όνομα": "name2",
"Διεύθυνση": "address2",
"Επίθε‌​το": "epitheto2",
"Κωδικός": 2,
"Προϊόντα": [
"subproduct2.1",
"subproduct2.2"
],
"Τηλέφων‌​ο": "2222222222"
}
]
}
The issue is that you are trying to deserialize into a list, but in your JSON the row data is not at the root level--it is inside an object. To fix, you need to deserialize to your serverdata class directly. But first, you will need to make a couple of changes to the attributes:
Mark your serverdata class with [DataContract]
Mark the Rows property inside serverdata with [DataMember(Name = "ΠρομηθευτέςResult")]
Mark the προμηθευτέςRow struct with [DataContract]
Your class should look like this:
[DataContract]
class serverdata
{
[DataMember(Name = "ΠρομηθευτέςResult")]
public προμηθευτέςRow[] Rows { get; set; }
[DataContract]
public struct προμηθευτέςRow
{
[DataMember(Name = "Κωδικός")]
public int Κωδικός { get; set; }
[DataMember(Name = "Όνομα")]
public string Όνομα { get; set; }
[DataMember(Name = "Επίθετο")]
public string Επίθετο { get; set; }
[DataMember(Name = "Τηλέφωνο")]
public string Τηλέφωνο { get; set; }
[DataMember(Name = "Διεύθυνση")]
public string Διεύθυνση { get; set; }
[DataMember(Name = "Mail")]
public string Mail { get; set; }
[DataMember(Name = "Προϊόντα")]
public string[] Προϊόντα { get; set; }
}
}
Then, change your code to deserialize to your serverdata class:
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(serverdata));
ServerData = (serverdata)ser.ReadObject(stream);
You can remove this line as it is no longer needed:
ServerData.Rows = result.ToArray();
After these changes you should find that the Rows array is filled correctly.

why instance variable returns null in c#? [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I have created a class and a global variable named as telephoneNumber. This variable is set in a method and used in another method. However this variable returns null. All methods and this global variable in the same class. Please help to understand this problem. Thanks a lot. My class is :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Net.Http;
using Newtonsoft.Json;
using System.Collections;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private string telephoneNumber;
private async void GetSingleLocationInfo(string href)
{
var hereNetUrl = string.Format(
href+"&accept=application/json"
);
// get data from HERE.net REST API
var httpClient = new HttpClient();
var hereNetResponse = await httpClient.GetStringAsync(hereNetUrl);
// deseralize JSON from Here.net
using (var tr = new StringReader(hereNetResponse))
using (var jr = new JsonTextReader(tr))
{
var rootObjectResponse = new JsonSerializer().Deserialize<Object>(jr);
String contacts = rootObjectResponse.ToString();
int startIndex = contacts.IndexOf("phone");
if (startIndex != -1)
{
String value = contacts.Substring(startIndex, 50);
telephoneNumber=value.Substring(value.IndexOf("+"));
}
else
{
telephoneNumber="";
}
}
}
private async void GeocodingWin8Query()
{
// build URL for Here.net REST service
string currentgeoLoc = "37.75075,-122.393472";
string queryString = "taxi";
string appID = "dV04O71v5F3f2W"; // MAKE SURE TO GET YOUR OWN from developers.here.net
object appCode = "8QVr5uSXwfcowDrA"; // MAKE SURE TO GET YOUR OWN from developers.here.net
var hereNetUrl = string.Format(
"http://demo.places.nlp.nokia.com/places/v1/discover/search?at={0}&q={1}&app_id={2}&app_code={3}&accept=application/json",
currentgeoLoc, queryString, appID, appCode);
// get data from HERE.net REST API
var httpClient = new HttpClient();
var hereNetResponse = await httpClient.GetStringAsync(hereNetUrl);
// deseralize JSON from Here.net
using (var tr = new StringReader(hereNetResponse))
using (var jr = new JsonTextReader(tr))
{
var rootObjectResponse = new JsonSerializer().Deserialize<RootObject>(jr);
List<Item> items=rootObjectResponse.results.items;
foreach(Item item in items){
string href = item.href;
GetSingleLocationInfo(href);
Console.WriteLine (telephoneNumber);//returns null
}
}
}
private void button1_Click(object sender, EventArgs e)
{
GeocodingWin8Query();
}
}
public class Category
{
public string id { get; set; }
public string title { get; set; }
public string href { get; set; }
public string type { get; set; }
}
public class Item
{
public List<double> position { get; set; }
public int distance { get; set; }
public string title { get; set; }
public Category category { get; set; }
public string icon { get; set; }
public string vicinity { get; set; }
public List<object> having { get; set; }
public string type { get; set; }
public string href { get; set; }
public string id { get; set; }
public double? averageRating { get; set; }
}
public class Context
{
public Location location { get; set; }
public string type { get; set; }
}
public class Search
{
public Context context { get; set; }
}
public class RootObject
{
public Results results { get; set; }
public Search search { get; set; }
}
}
So, where you call GetSingleLocationInfo, you are calling an async method. GetSingleLocationInfo calwill therefore run as far as the await statement then return stright to the caller, before the it httpClient.GetStringAsync(hereNetUrl); has returned.
To fix this, you need to await on your call GetSingleLocationInfo before trying to access the variable.
Since GetSingleLocationInfo is async it will be called asynchronously, so the Console.WriteLine (telephoneNumber); will be called before the GetSingleLocationInfo change it.
I think you should put an await when calling the method.
String.Substring returns NULL when no string found.
It's going to be "returning" null quite simply because telephoneNumber hasn't been set yet.
Your declaration of the variable private string telephoneNumber; doesn't set any value thus it is an empty string or null.
My guess would be your method where you print it out is being called before the method where you actually set telephoneNumber to have a value.

Categories