C2DM server side C# web service Error=InvalidRegistration - c#

I have searched everywhere and have not found an answer to my question. Let me get straight to the point. I have developed an android messaging app for the purpose of experimenting with C2DM. My app get's the registration ID and it gets displayed in my Log correctly. I then send that key through to my C# web service.
The C# Web service then applies for an auth token, which works fine. No problem so far. But, as soon as I POST my body items (registration_id, collapse_key, data.<key>, delay_while_idle) with my header(GoogleLogin auth=[AUTH_TOKEN]) I get the response: "Error=InvalidRegistration".
There is no reason for this not to work. And yes, I have tried every solution available here in stack overflow, but remained unsuccessful. Here is my main code for my server side:
WebRequest theRequest;
HttpWebResponse theResponse;
ArrayList theQueryData;
theRequest = WebRequest.Create("https://www.google.com/accounts/ClientLogin");
theRequest.Method = "POST";
theQueryData = new ArrayList();
String [] test = new String[5];
test[0] = "accountType=HOSTED_OR_GOOGLE";
test[1] = "Email=XXXXXXXXXXXXXXXXX";
test[2] = "Passwd=XXXXXXXXXXXXXXXX";
test[3] = "Source=Domokun";
test[4] = "service=ac2dm";
// Set the encoding type
theRequest.ContentType = "application/x-www-form-urlencoded";
// Build a string containing all the parameters
string Parameters = String.Join("&", (String[])test);
theRequest.ContentLength = Parameters.Length;
// We write the parameters into the request
StreamWriter sw = new StreamWriter(theRequest.GetRequestStream());
sw.Write(Parameters);
sw.Close();
// Execute the query
theResponse = (HttpWebResponse)theRequest.GetResponse();
StreamReader sr = new StreamReader(theResponse.GetResponseStream());
String value = sr.ReadToEnd();
String token = ParseForAuthTokenKey(value);
String value2 = "";
if (value != null)
{
WebRequest theRequest2;
HttpWebResponse theResponse2;
ArrayList theQueryData2;
theRequest2 = WebRequest.Create("http://android.clients.google.com/c2dm/send");
theRequest2.Method = "POST";
theQueryData2 = new ArrayList();
String[] test2 = new String[4];
test[0] = "registration_id=" + registerid;
test[1] = "collapse_key=0";
test[2] = "data.payload=Jannik was hier";
test[3] = "delay_while_idle=0";
// Set the encoding type
theRequest2.ContentType = "application/x-www-form-urlencoded";
// Build a string containing all the parameters
string Parameters2 = String.Join("&", (String[])test2);
theRequest2.ContentLength = Parameters2.Length;
theRequest2.Headers.Add(HttpRequestHeader.Authorization, "GoogleLogin auth=" + token);
// We write the parameters into the request
StreamWriter sw2 = new StreamWriter(theRequest2.GetRequestStream());
sw2.Write(Parameters2);
sw2.Close();
// Execute the query
theResponse2 = (HttpWebResponse)theRequest2.GetResponse();
StreamReader sr2= new StreamReader(theResponse2.GetResponseStream());
value2 = sr2.ReadToEnd();
public static bool RemoteCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true;
}
private static string ParseForAuthTokenKey(string webResponse)
{
string tokenKey = String.Empty;
if (webResponse.Contains(AuthTokenHeader))
{
tokenKey = webResponse.Substring(webResponse.IndexOf(AuthTokenHeader) + AuthTokenHeader.Length);
if (tokenKey.Contains(Environment.NewLine))
{
tokenKey.Substring(0, tokenKey.IndexOf(Environment.NewLine));
}
}
return tokenKey.Trim();
}
All I can think is that my C2DM account isn't registered correctly. Could this be it? Or are there an error in my code that I'm missing?

OK. I've found the solution.
string requestBody = string.Format("registration_id={0}&collapse_key{1}&data.key=value",
HttpUtility.UrlEncode(registrationId), "collapse");
string responseBody = null;
WebHeaderCollection requestHeaders = new WebHeaderCollection();
WebHeaderCollection responseHeaders = null;
requestHeaders.Add(HttpRequestHeader.Authorization, string.Format("GoogleLogin auth={0}", authToken));
httpClient.DoPostWithHeaders(c2dmPushUrl,
requestBody,
"application/x-www-form-urlencoded",
out responseBody,
out responseHeaders,
requestHeaders);
public bool DoPostWithHeaders(string url,
string requestBody,
string contextType,
out string responseBody,
out WebHeaderCollection responseHeaders,
WebHeaderCollection requestHeaders = null)
{
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
// FIRST SET REQUEST HEADERS
httpWebRequest.Headers = requestHeaders;
httpWebRequest.Method = "POST";
// THEN SET CONTENT TYPE - THE ORDER IS IMPORTANT
httpWebRequest.ContentType = contextType;
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(requestBody);
httpWebRequest.ContentLength = data.Length;
stream = httpWebRequest.GetRequestStream();
stream.Write(data, 0, data.Length);
....
....
....
}

Related

Creating a webservice that needs input parameters

So, basically I am creating a Windows Service that is going to consult a SOAP Service and after that return an item. To find that item, who made the service created 2 "filters". customerFilter and itemFilter.
So, when I create the web request I need to insert thoose 2 parameters.
I have this:
static string date = DateTime.Now.Date.ToString("yyyy_MM_dd");
static string pathLog = "Logs/LogGetSalesLineDiscount/" + date + "LogGetSalesLineDiscount.txt";
public static string[] CallWebService(IOrganizationService service)
{
var action = "http://...";
var url = "http://...";
var request = (HttpWebRequest)WebRequest.Create(url);
var postData = "customerFilter=" + Uri.EscapeDataString("TESTE");
postData += "&itemFilter=" + Uri.EscapeDataString("TESTE");
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "text/xml;charset=\"utf-8\"";
request.Headers.Add("SOAPAction", action);
request.ContentLength = data.Length;
request.Accept = "text/xml";
request.Credentials = new NetworkCredential("...", "...");
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
using (System.IO.StreamWriter file = new System.IO.StreamWriter(AppDomain.CurrentDomain.BaseDirectory + pathLog, true))
{
file.WriteLine(responseString);
}
return null;
}
}
If I have that, it will return an error 500. I don´t know why.
If I remove the action, it will return something about all the actions in the service...
Please help me, I dont know what to do....

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

HTTPWebResponse Failed to stream the response when passing "Combination Of Special characters" as password in Parameters

Working Scenario
When Passing first parameter "strPostData" (Not contain special characters in password) as below xml request means works fine and StreamReader providing the response as well & variable "strResult" loaded successfully.. "Request=janajana"
NOT Working Scenario
But when user password contains "special characters" in first parameter "strPostData" means, StreamReader failed to provide the response & variable "strResult" not loaded successfully.. "Request=<request><Username>jana</Username><Password>jana!##$%^&*()</Password></request>"
When passing password with combination of "special characters" when HTTPWebResponse failed & Streamreader also gets failed..
I have tried with Stream object statement with ..
//string tempString = Encoding.UTF8.GetString(buffer, 0, buffer.Length); &
Read Buffer code change
//Int32 count = await streamRead.ReadAsync(readBuffer, 0, 256); but not works ,,, please guide me anyone
public string[] GetResponseWebAPI(string strPostData, string strUrl)
{
string[] arrReturn = new string[3];
HttpWebResponse myHttpWebResponse = null;
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] buffer = encoding.GetBytes(strPostData);
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(strUrl);
myRequest.Timeout = 25000;// 25s
myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.ContentLength = buffer.Length;
myRequest.AllowAutoRedirect = true;
ServicePointManager.ServerCertificateValidationCallback = new
System.Net.Security.RemoteCertificateValidationCallback
(AcceptAllCertifications);
Stream newStream = myRequest.GetRequestStream();
newStream.Write(buffer, 0, buffer.Length);
newStream.Close();
myHttpWebResponse = (HttpWebResponse)myRequest.GetResponse();
WebHeaderCollection webHeader = myHttpWebResponse.Headers;
arrReturn[0] = webHeader["Statuscode"];
arrReturn[1] = webHeader["Statusmessage"];
Stream streamResponse = myHttpWebResponse.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
Char[] readBuffer = new Char[256];
int count = streamRead.Read(readBuffer,0, 256);
string strResult = string.Empty;
while (count > 0)
{
strResult += new String(readBuffer,0, count);
count = streamRead.Read(readBuffer,0, 256);
}
arrReturn[2] = strResult;
streamRead.Close();
streamResponse.Close();
myHttpWebResponse.Close();
return arrReturn;
}
I think the problem is in
myRequest.ContentType = "application/x-www-form-urlencoded";
So, from this line you are saying that content is URL-encoded and should be escaped.
So I assume, as a quick fix you could change
byte[] buffer = encoding.GetBytes(strPostData);
to
byte[] buffer = encoding.GetBytes(WebUtility.UrlEncode(strPostData));
or something.
But I do believe this intention could be expressed better. So consider using HttpClient and FormUrlEncodedContent:
public string[] GetResponseWebAPI(string strPostData, string strUrl)
{
string[] arrReturn = new string[3];
ServicePointManager.ServerCertificateValidationCallback =
(sender, certificate, chain, sslPolicyErrors) => true;
var handler = new HttpClientHandler()
{
AllowAutoRedirect = false
};
using (var client = new HttpClient(handler))
using (var content =
new FormUrlEncodedContent(new[] {new KeyValuePair<string, string>("Request", strPostData)}))
{
client.Timeout = TimeSpan.FromSeconds(25);
var response = client.PostAsync(strUrl, content).GetAwaiter().GetResult();
arrReturn[0] = response.Headers.GetValues("Statuscode").FirstOrDefault();
arrReturn[1] = response.Headers.GetValues("Statusmessage").FirstOrDefault();
arrReturn[2] = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
}
return arrReturn;
}

Send file to Trimble Connect (HTTP://connect.trimble.com/)

I will need to send a some file to service (connect.trimble.com).
I do not understand, how upload a file to the service?
I have API instruction:
and I use this code:
string result = string.Empty;
string Url = "https://app.prod.gteam.com/tc/api/2.0/auth";
string TypeContent = "application/json";
string Method = "POST";
object obj = new
{
emailAddress = "MyMail",
key = "MyKey"
};
string Header = string.Empty;
result = RequestPost(Url, TypeContent, Method, Header, obj);
var qwe = result.Split(new char[] { '"' });
Header = "Bearer " + qwe[3];
Url = "https://app.prod.gteam.com/tc/api/2.0/files";
TypeContent = "multipart/form-data";
Method = "POST";
obj = new
{
parentId = "yVWsT_jewHs"
};
result = RequestPost(Url, TypeContent, Method, Header, obj);
private static string RequestPost(string Url, string TypeContent, string Method, string Header, object obj)
{
string result = string.Empty;
var httpWebRequest = (HttpWebRequest)WebRequest.Create(Url);
httpWebRequest.ContentType = TypeContent;
httpWebRequest.Method = Method;
if (!string.IsNullOrEmpty(Header))
{
httpWebRequest.Headers.Add("Authorization", Header);
}
if (obj != null)
{
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize(obj);
streamWriter.Write(json);
}
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
return result;
}
This code return error:
The remote server returned an error: (400) Bad Request.
I found answer myself. This topic can be closed.
string Url = "app.prod.gteam.com/tc/api/2.0/files?parentId=bHHkdeBSizA";
bHHkdeBSizA - This ID is parent folder ID, where the file will located, in current API parentId may equals rootId.
public static void UploadFile(string url, string filePath, string Header)
{
using (var client = new WebClient())
{
if (!string.IsNullOrEmpty(Header))
{
client.Headers.Add("Authorization", Header);
}
byte[] result = client.UploadFile(url, filePath);
string responseAsString = Encoding.Default.GetString(result);
}
}

Remote HTTP Post with C# [duplicate]

This question already has answers here:
Send HTTP POST request in .NET
(16 answers)
Closed 9 years ago.
How do you do a Remote HTTP Post (request) in C#?
This is code from a small app I wrote once to post a form with values to a URL. It should be pretty robust.
_formValues is a Dictionary<string,string> containing the variables to post and their values.
// encode form data
StringBuilder postString = new StringBuilder();
bool first=true;
foreach (KeyValuePair pair in _formValues)
{
if(first)
first=false;
else
postString.Append("&");
postString.AppendFormat("{0}={1}", pair.Key, System.Web.HttpUtility.UrlEncode(pair.Value));
}
ASCIIEncoding ascii = new ASCIIEncoding();
byte[] postBytes = ascii.GetBytes(postString.ToString());
// set up request object
HttpWebRequest request;
try
{
request = WebRequest.Create(url) as HttpWebRequest;
}
catch (UriFormatException)
{
request = null;
}
if (request == null)
throw new ApplicationException("Invalid URL: " + url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postBytes.Length;
// add post data to request
Stream postStream = request.GetRequestStream();
postStream.Write(postBytes, 0, postBytes.Length);
postStream.Close();
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
I use this very simple class:
public class RemotePost{
private System.Collections.Specialized.NameValueCollection Inputs
= new System.Collections.Specialized.NameValueCollection() ;
public string Url = "" ;
public string Method = "post" ;
public string FormName = "form1" ;
public void Add( string name, string value ){
Inputs.Add(name, value ) ;
}
public void Post(){
System.Web.HttpContext.Current.Response.Clear() ;
System.Web.HttpContext.Current.Response.Write( "<html><head>" ) ;
System.Web.HttpContext.Current.Response.Write( string .Format( "</head><body onload=\"document.{0}.submit()\">" ,FormName)) ;
System.Web.HttpContext.Current.Response.Write( string .Format( "<form name=\"{0}\" method=\"{1}\" action=\"{2}\" >" ,
FormName,Method,Url)) ;
for ( int i = 0 ; i< Inputs.Keys.Count ; i++){
System.Web.HttpContext.Current.Response.Write( string .Format( "<input name=\"{0}\" type=\"hidden\" value=\"{1}\">" ,Inputs.Keys[i],Inputs[Inputs.Keys[i]])) ;
}
System.Web.HttpContext.Current.Response.Write( "</form>" ) ;
System.Web.HttpContext.Current.Response.Write( "</body></html>" ) ;
System.Web.HttpContext.Current.Response.End() ;
}
}
And you use it thusly:
RemotePost myremotepost = new RemotePost() ;
myremotepost.Url = "http://www.jigar.net/demo/HttpRequestDemoServer.aspx" ;
myremotepost.Add( "field1" , "Huckleberry" ) ;
myremotepost.Add( "field2" , "Finn" ) ;
myremotepost.Post() ;
Very clean, easy to use and encapsulates all the muck. I prefer this to using the HttpWebRequest and so forth directly.
You can use WCF or create a WebRequest
var httpRequest = (HttpWebRequest)WebRequest.Create("http://localhost/service.svc");
var httpRequest.Method = "POST";
using (var outputStream = httpRequest.GetRequestStream())
{
// some complicated logic to create the message
}
var response = httpRequest.GetResponse();
using (var stream = response.GetResponseStream())
{
// some complicated logic to handle the response message.
}
Also System.Net.WebClient
Use the WebRequest.Create() and set the Method property.
Im using the following piece of code for calling webservices using the httpwebrequest class:
internal static string CallWebServiceDetail(string url, string soapbody,
int timeout) {
return CallWebServiceDetail(url, soapbody, null, null, null, null,
null, timeout);
}
internal static string CallWebServiceDetail(string url, string soapbody,
string proxy, string contenttype, string method, string action,
string accept, int timeoutMilisecs) {
var req = (HttpWebRequest) WebRequest.Create(url);
if (action != null) {
req.Headers.Add("SOAPAction", action);
}
req.ContentType = contenttype ?? "text/xml;charset=\"utf-8\"";
req.Accept = accept ?? "text/xml";
req.Method = method ?? "POST";
req.Timeout = timeoutMilisecs;
if (proxy != null) {
req.Proxy = new WebProxy(proxy, true);
}
using(var stm = req.GetRequestStream()) {
XmlDocument doc = new XmlDocument();
doc.LoadXml(soapbody);
doc.Save(stm);
}
using(var resp = req.GetResponse()) {
using(var responseStream = resp.GetResponseStream()) {
using(var reader = new StreamReader(responseStream)) {
return reader.ReadToEnd();
}
}
}
}
This can be easily used to call a webservice
public void TestWebCall() {
const string url =
"http://www.ecubicle.net/whois_service.asmx/HelloWorld";
const string soap =
#"<soap:Envelope xmlns:soap='about:envelope'>
<soap:Body><HelloWorld /></soap:Body>
</soap:Envelope>";
string responseDoc = CallWebServiceDetail(url, soap, 1000);
XmlDocument doc = new XmlDocument();
doc.LoadXml(responseDoc);
string response = doc.DocumentElement.InnerText;
}
HttpWebRequest HttpWReq =
(HttpWebRequest)WebRequest.Create("http://www.google.com");
HttpWebResponse HttpWResp = (HttpWebResponse)HttpWReq.GetResponse();
Console.WriteLine(HttpWResp.StatusCode);
HttpWResp.Close();
Should print "OK" (200) if the request was successful
The problem when beginning with high-level language like C#, Java or PHP is that people may have never known how simple the underground is in reality. So here’s a short introduction:
http://reboltutorial.com/blog/raw-http-request/

Categories

Resources