Bing translator in WPF - c#

I made a web application which translates the entered text into another language. I used Microsoft's Bing translator service for this and it works perfectly. But when i tried this in WPF application it gives an exception which is commented below. The exception says:
An unhandled exception of type'System.Runtime.Serialization.InvalidDataContractException' occurred in System.Runtime.Serialization.dll Additional information: Type 'TranslatorWPF.AdmAccessToken' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. If the type is a collection, consider marking it with the CollectionDataContractAttribute.
Any help with this!!
Code
string clientID = "abc";
string clientSecret = "........";
String strTranslatorAccessURI = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13";
String strRequestDetails = string.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=http://api.microsofttranslator.com", HttpUtility.UrlEncode(clientID), HttpUtility.UrlEncode(clientSecret));
System.Net.WebRequest webRequest = System.Net.WebRequest.Create(strTranslatorAccessURI);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(strRequestDetails);
webRequest.ContentLength = bytes.Length;
using (System.IO.Stream outputStream = webRequest.GetRequestStream())
{
outputStream.Write(bytes, 0, bytes.Length);
}
System.Net.WebResponse webResponse = webRequest.GetResponse();
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(AdmAccessToken));
//Get deserialized object from JSON stream
AdmAccessToken token = (AdmAccessToken)serializer.ReadObject(webResponse.GetResponseStream()); //** this line throws an exception
string headerValue = "Bearer " + token.access_token;
string txtToTranslate = text.Text;
string uri = "http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + System.Web.HttpUtility.UrlEncode(txtToTranslate) + "&from=en&to=ur";
System.Net.WebRequest translationWebRequest = System.Net.WebRequest.Create(uri);
translationWebRequest.Headers.Add("Authorization", headerValue);
System.Net.WebResponse response = null;
response = translationWebRequest.GetResponse();
System.IO.Stream stream = response.GetResponseStream();
System.Text.Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
System.IO.StreamReader translatedStream = new System.IO.StreamReader(stream, encode);
System.Xml.XmlDocument xTranslation = new System.Xml.XmlDocument();
xTranslation.LoadXml(translatedStream.ReadToEnd());
urdu.Text = xTranslation.InnerText;

Related

WEB API C# REPONSE HANGS (HttpWebResponse)http.GetResponse()

Am doing an WEB API .net 4.62 that /Token with username password and grant_type to get access token once its generated i woul like to get it value of access_token.This does not happen but when i take the same code to a windows form aplication I am able to get it what could be wrong. It hangs on using (HttpWebResponse response = (HttpWebResponse)http.GetResponse())
try
{
string myParameters = "username=value1&password=value2&grant_type=password";
string baseAddress = "http://localhost:50128/token";
var http = (HttpWebRequest)WebRequest.Create(new Uri(baseAddress));
http.Accept = "application/x-www-form-urlencoded";
http.ContentType = "application/x-www-form-urlencoded";
http.Method = "POST";
string parsedContent = myParameters;
ASCIIEncoding encoding = new ASCIIEncoding();
Byte[] bytes = encoding.GetBytes(parsedContent);
Stream newStream = http.GetRequestStream();
newStream.Write(bytes, 0, bytes.Length);
newStream.Close();
http.ServicePoint.Expect100Continue = false;
http.ProtocolVersion = HttpVersion.Version11;
http.Timeout = 2000;
using (HttpWebResponse response = (HttpWebResponse)http.GetResponse())
{
var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();
JObject json = JObject.Parse(content);
var message = json.SelectToken("access_token").ToString();
Console.Write(message);
}
}
catch (Exception ex)
{
//Handle the exceptions that could appear
}
change the using block like this and also convert your function to "async".
using (HttpWebResponse response = (HttpWebResponse)await Task.Factory.FromAsync(http.BeginGetResponse, http.EndGetResponse, null).ConfigureAwait(false))
let me know if it works.

json-rpc server over nancy

We've started using nancy in our open source project; https://github.com/CoiniumServ/coinium (a stratum/getwork/gbt pool server).
We basically need to support api calls over json-rpc. We're getting request similar to this;
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(Url);
webRequest.Credentials = new NetworkCredential(User, Password);
webRequest.ContentType = "application/json-rpc";
webRequest.Method = "POST";
string jsonParam = (paramString != null) ? "\"" + paramString + "\"" : "";
string request = "{\"id\": 0, \"method\": \"" + method + "\", \"params\": [" + jsonParam + "]}";
// serialize json for the request
byte[] byteArray = Encoding.UTF8.GetBytes(request);
webRequest.ContentLength = byteArray.Length;
using (Stream dataStream = webRequest.GetRequestStream())
dataStream.Write(byteArray, 0, byteArray.Length);
string reply = "";
using (WebResponse webResponse = webRequest.GetResponse())
using (Stream str = webResponse.GetResponseStream())
using (StreamReader reader = new StreamReader(str))
reply = reader.ReadToEnd();
return reply;
So basically the request is sent to / route with content-type application/json-rpc and we need to parse the inner provided request.
I've checked documentation but couldn't find my way out, does nancy support json-rpc?
Can anybody point me to right direction?
I've put a sample route as;
Post["/"] = #params =>
{
return "test";
};
but within the #params or Context couldn't find the actual json-rpc request string to parse.
Try either model binding (https://github.com/NancyFx/Nancy/wiki/Model-binding) or looking at Request.Body directly.

I'm facing the error Stream.Length throws NotSupportedException

I am trying to POST some data from ASP.Net application to PHP using HttpWebRequest object. But when I try reading the Request content using
Stream myStream = myWebReq.GetRequestStream();
I am getting an error
'responseStream.Length' threw an exception of type 'System.NotSupportedException'.
Length = 'dataStream.Length' threw an exception of type 'System.NotSupportedException'
Position = 'dataStream.Position' threw an exception of type 'System.NotSupportedException'
Here is the code
string strURL = null;
HttpWebRequest myWebReq = default(HttpWebRequest);
HttpWebResponse myWebResp = default(HttpWebResponse);
byte[] byteData = null;
StreamReader sr = default(StreamReader);
strURL = "http://people.com.pk/nppm/hrms_ppm_service.php?dump=1";
myWebReq = (HttpWebRequest)WebRequest.Create(strURL);
myWebReq.ContentType = "application/x-www-form-urlencoded; charset=utf-8";
myWebReq.Method = "POST";
Label1.Text = Newtonsoft.Json.JsonConvert.SerializeObject(batches).ToString();
byteData = UTF8Encoding.UTF8.GetBytes(Label1.Text);
myWebReq.ContentLength = byteData.Length;
myWebReq.KeepAlive = true;
if (myWebReq.Proxy != null)
{
myWebReq.Proxy.Credentials = CredentialCache.DefaultCredentials;
}
Stream myStream = myWebReq.GetRequestStream();
if (byteData.Length > 0)
{
myStream.Write(byteData, 0, byteData.Length);
myStream.Close();
}
myWebResp = (HttpWebResponse)myWebReq.GetResponse();
sr = new StreamReader(myWebResp.GetResponseStream());
string strJSON__2 = sr.ReadToEnd();
Label1.Text = strJSON__2;
Just check your HttpWebRequest.DefaultCachePolicy property.
As the documentation suggest that HttpWebRequest.GetRequestStream method will throw NotSupportedException only when the request cache validator indicates that the response for the request can be served from the cache; however, requests that write data must not use the cache. This exception can occur if you are using a custom cache validator that is incorrectly implemented.

UnSupported Media Type when Calling REST Web Service

I am calling a REST web service which has given me this documentation
HTTP Method: POST
Path: /commit/{path}/add-node
Response Status 200, 302, 403, 404, 409, 503
Form Parameters
- name : attribute name
- message : commit message
Based on this documentation. I have written following C# code.
string restUrl = webServiceurl + "/commit/" + path + "/add-node";
restUrl = restUrl + "?name=" + nodeName + "&message=" + commitMessage;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(restUrl);
request.Method = "POST";
request.ContentType = #"application/json";
using (WebResponse response = request.GetResponse()) {
using (StreamReader reader = new StreamReader(response.GetResponseStream())) {
output = reader.ReadToEnd();
}
}
I also tried
string restUrl = webServiceurl + "/commit/" + path + "/add-node";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(restUrl);
request.Method = "POST";
request.ContentType = #"application/json";
var param = new { name = nodeName, message = commitMessage };
Stream reqStream = null;
string output = null;
try {
byte[] buffer = Encoding.GetEncoding("UTF-8").GetBytes(
JsonConvert.SerializeObject(param)
);
request.ContentLength = buffer.Length;
reqStream = request.GetRequestStream();
reqStream.Write(buffer, 0, buffer.Length);
using (WebResponse response = request.GetResponse()) {
using (StreamReader reader = new StreamReader(response.GetResponseStream())) {
output = reader.ReadToEnd();
}
}
} catch (Exception ex) {
.....
}
Unfortunately in both cases, I get 415 Unsupported Media Type in both cases. What is wrong with my code?
The web Services is a REST based web service written in Java.
According to this forum post the ContentType property may not be supported from the Java web service. Are you sure it accepts application/json?

Restful wcf Service error 'Unable to deserialize XML body with root name

I have written a RESFful service for a phone app.
I am not sure what am I doing wrong? I tried to test it with multiple content type settings but no luck.
The data from a phone app is coming encoded in following format.
PHNhbWxwOlJlc3BvbnNlIHhtbG5zOnNhbWxwPSJ1cm46b2FzaXM6bmFtZXM6dGM6U0FNTDoyLjA6cHJvdG9jb2wiPjxzYW1scDpTdGF0dXM+PHNhbWxwOlN0YXR1c0NvZGU+ aGVyVmFsdWU+PC94ZW5jOkNpcGhlckRhdGE+PC94ZW5jOkVuY3J5cHRlZERhdGE+PC9zYW1sOkVuY3J5cHRlZEFzc2VydGlvbj48L3NhbWxwOlJlc3BvbnNlPg==";
This is the definition in the interface:
[OperationContract]
[WebInvoke]
String GetUserInfo(String authenticateRequest);
I get error: with following test code.
'Unable to deserialize XML body with root name 'Binary' and root namespace '' (for operation 'GetMobileCheckCapture' and contract ('IMobileCC', 'http://tempuri.org/')) using DataContractSerializer
This is how I am trying to test the service:
String encryptedSAML =
PHNhbWxwOlJlc3BvbnNlIHhtbG5zOnNhbWxwPSJ1cm46b2FzaXM6bmFtZXM6dGM6U0FNTDoyLjA6cHJvdG9jb2wiPjxzYW1scDpTdGF0dXM+PHNhbWxwOlN0YXR1c0NvZGU+ aGVyVmFsdWU+PC94ZW5jOkNpcGhlckRhdGE+PC94ZW5jOkVuY3J5cHRlZERhdGE+PC9zYW1sOkVuY3J5cHRlZEFzc2VydGlvbj48L3NhbWxwOlJlc3BvbnNlPg==";
HttpWebRequest req = WebRequest.Create("http://localhost/Services/Mservice.svc/GetUserInfo") as HttpWebRequest;
req.KeepAlive = false;
req.Method = "POST";
req.ContentType = "text/xml; encoding='utf-8'";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] bDataToPass = encoding.GetBytes(encryptedSAML);
req.ContentLength = bDataToPass.Length;
using (Stream dataStream = req.GetRequestStream())
{
dataStream.Write(bDataToPass, 0, bDataToPass.Length);
}
try
{
using (WebResponse webresponse = req.GetResponse())
{
StreamReader reader = null;
string responses = "";
string StatusDescription = ((HttpWebResponse)webresponse).StatusDescription;
if (((HttpWebResponse)webresponse).StatusCode != HttpStatusCode.OK)
{
// Console.Write();
}
reader = new StreamReader(webresponse.GetResponseStream());
responses = reader.ReadToEnd();
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(responses.Replace("&", "&"));
response = xmldoc;
}
}
catch (WebException e)
{
using (WebResponse response2 = e.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse)response2;
Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
using (Stream data = response2.GetResponseStream())
{
string text = new StreamReader(data).ReadToEnd();
Console.WriteLine(text);
}
}
}
Have you tried to use UTF-8 encoding instead of ASCII?
HttpWebRequest req = WebRequest.Create("http://localhost/Services/Mservice.svc/GetUserInfo") as HttpWebRequest;
req.KeepAlive = false;
req.Method = "POST";
req.ContentType = "text/xml; encoding='utf-8'";
UTF8Encoding encoding = new UTF8Encoding();
byte[] bDataToPass = encoding.GetBytes(encryptedSAML);
req.ContentLength = bDataToPass.Length;

Categories

Resources