Failing to return xml in return statement - c#

I am still trying to from a webservuce I have the following code crafted, but for some reason when it comes to the return value its null even though when i debug the xml string value it is indead there.
public XmlTextReader readXML(string postcode, string response, string accessCode)
{
WebRequest wrURL;
Stream objStream;
string strURL;
string url = "http://pcls1.craftyclicks.co.uk/xml/rapidaddress?postcode=" + postcode + "&response=" + response + "&key=" + accessCode;
wrURL = WebRequest.Create(url);
string xml = new WebClient().DownloadString(url);
objStream = wrURL.GetResponse().GetResponseStream();
StreamReader objSReader = new StreamReader(objStream);
strURL = objSReader.ReadToEnd().ToString(); #####but here it has the xml data ?####
XmlTextReader reader = new XmlTextReader(new StringReader(strURL));
return reader;#######here its empty ????#####
}
Edit
I am still not getting a response here but yet when i view it in the actual browser from the url produced within the code it displays the following
<CraftyResponse><address_data_formatted><delivery_point><organisation_name>THE BAKERY</organisation_name><department_name/><line_1>1 HIGH STREET</line_1><line_2>CRAFTY VALLEY</line_2><udprn>12345678</udprn></delivery_point><delivery_point><organisation_name>FILMS R US</organisation_name><department_name/><line_1>3 HIGH STREET</line_1><line_2>CRAFTY VALLEY</line_2><udprn>12345679</udprn></delivery_point><delivery_point><organisation_name>FAMILY BUTCHER</organisation_name><department_name/><line_1>7 HIGH STREET</line_1><line_2>CRAFTY VALLEY</line_2><udprn>12345680</udprn></delivery_point><delivery_point><organisation_name/><department_name/><line_1>BIG HOUSE, HIGH STREET</line_1><line_2>CRAFTY VALLEY</line_2><udprn>12345681</udprn></delivery_point><delivery_point><organisation_name/><department_name/><line_1>LITTLE COTTAGE</line_1><line_2>17 HIGH STREET, CRAFTY VALLEY</line_2><udprn>12345682</udprn></delivery_point><delivery_point_count>5</delivery_point_count><town>BIG CITY</town><postal_county>POSTAL COUNTY</postal_county><traditional_county>TRADITIONAL COUNTY</traditional_county><postcode>AA1 1AA</postcode></address_data_formatted></CraftyResponse>
I tried method 2 mentioned below but stil no luck
public XmlTextReader readXML(string postcode, string response, string accessCode)
{
string url = $"http://pcls1.craftyclicks.co.uk/xml/rapidaddress?postcode={postcode}&response={response}&key={accessCode}";
using (Stream objStream = WebRequest.Create(url)?.GetResponse().GetResponseStream())
{
return new XmlTextReader(new StringReader(new StreamReader(objStream)?.ReadToEnd()));
}//Dispose the Stream
}
Animated gif to show debuging

When working with IDisposable Objects you should consider using using
public XmlTextReader readXML(string postcode, string response, string accessCode)
{
string strURL = string.Empty;
string url = "http://pcls1.craftyclicks.co.uk/xml/rapidaddress?postcode=" + postcode + "&response=" + response + "&key=" + accessCode;
WebRequest wrURL = WebRequest.Create(url);
//string xml = new WebClient().DownloadString(url); //What is this for ? I dont see you using this in your code ?!
using(Stream objStream = wrURL.GetResponse().GetResponseStream())
{
using(StreamReader objSReader = new StreamReader(objStream))
{
return new XmlTextReader(new StringReader(objSReader.ReadToEnd()));
}//Dispose the StreamReader
}//Dispose the Stream
}
Try if the provided code fixes it.
EDIT:
To shorten your code you could use:
string url = $"http://pcls1.craftyclicks.co.uk/xml/rapidaddress?postcode={postcode}&response={response}&key={accessCode}";
using(Stream objStream = WebRequest.Create(url)?.GetResponse().GetResponseStream())
{
return new XmlTextReader(new StringReader(new StreamReader(objStream)?.ReadToEnd()));
}//Dispose the Stream
EDIT:
public XmlTextReader ReadXml(string postcode, string response, string accessCode)
{
//Create URL
string url = $"http://pcls1.craftyclicks.co.uk/xml/rapidaddress?postcode={postcode}&response={response}&key={accessCode}";
try
{
//Create WebRequest
WebRequest request = WebRequest.Create(url);
using (Stream responseStream = request.GetResponse().GetResponseStream())
{
if (responseStream != null)
{
using (TextReader textReader = new StreamReader(responseStream))
{
XmlTextReader reader = new XmlTextReader(textReader);
Debug.Assert(reader != null, "Reader is NULL");
return reader;
}
}
throw new Exception("ResponseStream is NULL");
}
}
catch (WebException ex)
{
//Handle exceptions here
throw;
}
}
Can you try this snippet ?
Side Note:
There is another overload in XmlTextReader which looks like this:
public XmlTextReader(string url);
public XmlTextReader readXML(string postcode, string response, string accessCode)
{
//Create URL
string url = $"http://pcls1.craftyclicks.co.uk/xml/rapidaddress?postcode={postcode}&response={response}&key={accessCode}";
return new XmlTextReader(url);
}
You can also try this one !

Related

How do I download a CSV file to a string from an https URL?

The code that I have listed here works when I ReadAllText from a local file. What I need to be able to do is replace the path "C:\LocalFiles\myFile.csv" with "https://mySite.blah/myFile.csv".
I have tried several methods, but can't seem to be able to get the csv file loaded into a string variable. If I could just do that, then the code would work for me.
var csv = System.IO.File.ReadAllText(#"C:\LocalFiles\myFile.csv");
StringBuilder sb = new StringBuilder();
using (var p = ChoCSVReader.LoadText(csv).WithFirstLineHeader())
{
p.Configuration.NullValue = null;
if (p.Configuration.CSVRecordFieldConfigurations.IsNullOrEmpty())
{
p.Configuration.NullValue = null;
}
// ChoIgnoreFieldValueMode.DBNull = ChoIgnoreFieldValueMode.Empty();
using (var w = new ChoJSONWriter(sb))
w.Write(p);
}
string fullJson = sb.ToString();
If I simply replace the path, I get an error message that says that the path is invalid.
You need to get the string using a web request:
string urlAddress = "https://mySite.blah/myFile.csv";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream receiveStream = response.GetResponseStream();
StreamReader readStream = null;
if (response.CharacterSet == null)
{
readStream = new StreamReader(receiveStream);
}
else
{
readStream = new StreamReader(receiveStream,
Encoding.GetEncoding(response.CharacterSet));
}
string data = readStream.ReadToEnd();
response.Close();
readStream.Close();
}
or using a Webclient:
WebClient wc = new WebClient();
string data = wc.DownloadString("https://mySite.blah/myFile.csv");
Then pass data into your reader instead of using the System.IO.File.ReadAllText(#"C:\LocalFiles\myFile.csv");
Both of the above examples assume that the file is publicly accessible at that url without authentication or specific header values.
Replace this line
var csv = System.IO.File.ReadAllText(#"C:\LocalFiles\myFile.csv");
with
string result = client.GetStringAsync("https://mySite.blah/myFile.csv").Result;
or
var textFromFile = (new WebClient()).DownloadString("https://mySite.blah/myFile.csv");
There are many other ways to do it as well. Just google it.

Google speech to text API in C# stopped working

I am trying to convert voice to text using Google Speech API. I have a sample code below. It was working fine, it stopped working suddenly and now it always throws the error - 400 bad request. I am using GOOGLE_SPEECH_KEY for authentication without OAuth2 token.
Not sure what exactly I'm missing. Do I need to create OAuth authentication or do I need to modify any console settings in google portal or need to modify the code itself ? Please help!
I used all the below api's and same 400 error:
1. url = "https://speech.googleapis.com/v1beta1/speech:syncrecognize?key=" + ACCESS_GOOGLE_SPEECH_KEY;
2. url = "https://speech.googleapis.com/v1/speech:recognize?key=" + ACCESS_GOOGLE_SPEECH_KEY;
3. url = "https://speech.googleapis.com/v1p1beta1/speech:recognize?key=" + ACCESS_GOOGLE_SPEECH_KEY;
public static string GoogleSpeechToTextApi(string flacUrl)
{
string pTranscriptText = "None", pTranscriptConfidence = "";
string appendText = "";
try
{
// Stream responseStream = imageResponse.GetResponseStream();
if (flacUrl != null)
{
string blobURI = flacUrl;
WebClient myWebClient = new WebClient();
Stream fileStream = myWebClient.OpenRead(blobURI);
byte[] BA_AudioFile = null;
using (var stream2 = new MemoryStream())
{
fileStream.CopyTo(stream2);
stream2.SetLength(stream2.Length);
stream2.Read(stream2.GetBuffer(), 0, (int)stream2.Length);
BA_AudioFile = stream2.GetBuffer();
}
string audioInput = Convert.ToBase64String(BA_AudioFile);
Config config = new Config();
config.encoding = "flac";
config.languageCode = "en";
config.sampleRate = "8000";
Audio audio = new Audio();
audio.content = audioInput;
JsonRequest request = new JsonRequest();
request.config = config;
request.audio = audio;
string json = JsonConvert.SerializeObject(request);
string url = "https://speech.googleapis.com/v1beta1/speech:syncrecognize?key=" + ACCESS_GOOGLE_SPEECH_KEY; // original api url
//url = "https://speech.googleapis.com/v1/speech:recognize?key=" + ACCESS_GOOGLE_SPEECH_KEY; // tested with this
//url = "https://speech.googleapis.com/v1p1beta1/speech:recognize?key=" + ACCESS_GOOGLE_SPEECH_KEY; // tested with this
WebRequest webRequest = WebRequest.Create(url);
webRequest.Method = "POST";
byte[] byteArray = Encoding.UTF8.GetBytes(json);
webRequest.ContentLength = byteArray.Length;
Stream dataStream = webRequest.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = webRequest.GetResponse();
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
RootObject ro = JsonConvert.DeserializeObject<RootObject>(responseFromServer);
dynamic JsonArray = JsonConvert.DeserializeObject(responseFromServer);
var jsonResult = JsonArray["results"];
foreach (var item in jsonResult)
{
appendText += item.alternatives[0].transcript;
}
}
return appendText;
}
catch (Exception ex)
{
return appendText = "Error";
}
}
}
}
Error 400 means that your request is not correct. You can try encoding = linear16, audioChannelCount = 2 and sampleRateHertz = 16000 with file wav.
Btw, you can pass your key in header request instead in your url

Get the HTML result even if we get an exception with this code

I would like to return the HTML result of a page with this code below, even if I get a 403 response code for example, so if it throw an exception.
This is the current code I have, and as you can see I would like to return the HTML result of the page when an exception is throwed too.
public string authenticate(string user, string pass)
{
try
{
var request = (HttpWebRequest)WebRequest.Create("https://authserver.mojang.com/authenticate");
request.ContentType = "application/json";
request.Method = "POST";
using (var writer = new StreamWriter(request.GetRequestStream()))
{
string json = "{\"agent\":{\"name\":\"Minecraft\",\"version\":1},\"username\":\"" + user + "\",\"password\":\"" + pass + "\",\"clientToken\":\"6c9d237d-8fbf-44ef-b46b-0b8a854bf391\"}";
writer.Write(json);
writer.Flush();
writer.Close();
var response = (HttpWebResponse)request.GetResponse();
using (var reader = new StreamReader(response.GetResponseStream()))
{
return reader.ReadToEnd(); // the html result
}
}
}
catch (Exception)
{
return "the html result";
}
}
Thanks for help.

Calling generic handler asp c#

I have generic handler which return me XML in string. How I should call him?
int userid = 1;
string xmlString = string.Format("~/XMLHandler.ashx?userId={0}", userid); // here I need returned string from handler
System.IO.StreamWriter file = new System.IO.StreamWriter("e:\\vypujcky.xml");
file.WriteLine(xmlString);
file.Close();
You can use System.Net.WebClient.DownloadString() to download the resource:
int userid = 1;
Uri resourceUri = new Uri(new Uri(Request.Url.Host), string.Format("XMLHandler.ashx?userId={0}", userid));
System.Net.WebClient webClient = new System.Net.WebClient();
string xmlString = webClient.DownloadString(resourceUri);
// rest of the code is the same
like this
int userid = 1;
string xmlString = string.Format("~/XMLHandler.ashx?userId={0}", userid);
WebRequest req = WebRequest.Create(Server.MapPath("~\")+xmlString);
req.Proxy = null;
req.Method = "POST";
string responseFromServer="";
try
{
WebResponse response = req.GetResponse();
Stream dataStream = response.GetResponseStream();
var statusCode = ((HttpWebResponse)response).StatusCode;
StreamReader reader = new StreamReader(dataStream);
responseFromServer = reader.ReadToEnd();
using(System.IO.StreamWriter file = new System.IO.StreamWriter("e:\\vypujcky.xml"))
{
file.WriteLine(responseFromServer);
}
}
catch (WebException ex)
{
}

How to convert Office 365 �ɂ����鑼�̃��[�U�[�̃��[���{�b�N�X�ւ̃A�N�Z�X�Ɋւ���K�C�h�`���`���[�g���A��

I am reading source of the following url but the title is coming as bunch of ?? marks, how do I convert it to actual language that the web page is presenting.
http://support.microsoft.com/common/survey.aspx?scid=sw;ja;3703&showpage=1
private string[] getTitleNewUrl()
{
string url = #"http://support.microsoft.com/common/survey.aspx?scid=sw;ja;3703&showpage=1";
string[] titleNewUrl = new string[2];
var navigatedUrl = string.Empty;
string title = string.Empty;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Credentials = System.Net.CredentialCache.DefaultCredentials;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
navigatedUrl = response.ResponseUri.ToString(); **//this returns [http://support.microsoft.com/default.aspx?scid=gp;en-us;fmserror][1]**
StreamReader sr = new StreamReader(response.GetResponseStream());
var htmlSource = sr.ReadToEnd();
Match m = Regex.Match(htmlSource, #"<title>\s*(.+?)\s*</title>");
if (m.Success)
{
title = m.Groups[1].Value;
}
titleNewUrl[0] = title;
titleNewUrl[1] = navigatedUrl;
}
}
catch (Exception ex)
{
MessageBox.Show("Invalid URL: " + navigatedUrl + " Error: " + ex.Message);
}
return titleNewUrl;
}
Thanks
Here is the answer
public string GetResponseStream(string sURL)
{
string strWebPage = "";
// create request
System.Net.WebRequest objRequest = System.Net.HttpWebRequest.Create(sURL);
// get response
System.Net.HttpWebResponse objResponse;
objResponse = (System.Net.HttpWebResponse)objRequest.GetResponse();
// get correct charset and encoding from the server's header
string Charset = objResponse.CharacterSet;
Encoding encoding = Encoding.GetEncoding(Charset);
// read response
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream(), encoding))
{
strWebPage = sr.ReadToEnd();
// Close and clean up the StreamReader
sr.Close();
}
return strWebPage;
}

Categories

Resources