How to use PennySMS in c#.net? - c#

Has anyone used PennySMS's web services? (https://www.pennysms.com/docs) I'm having some difficulty doing a successful HttpPost request.
Update:
I'm a n00b to Web Services. I don't even know if I can complete this type of request server-side. I've replaced the actual info in the params with example info.
protected void bText_Click(object sender, EventArgs e)
{
string XML = "<?xml version=\"1.0\"?>"
+"<methodCall>"
+"<methodName>send</methodName>"
+" <params>"
+" <param>"
+ " <value><string>MY KEY</string></value>"
+" </param>"
+" <param>"
+ " <value><string>service#example.com</string></value>"
+" </param>"
+" <param>"
+ " <value><string>555555555</string></value>"
+" </param>"
+" <param>"
+" <value><string>Test Message</string></value>"
+" </param>"
+" </params>"
+"</methodCall>";
SendText("http://api.pennysms.com/xmlrpc", "XML");
}
public void SendText(string _URL, string _parameters)
{
WebRequest request = WebRequest.Create(_URL);
request.Method = "POST";
string postData = _parameters;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "text/xml";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
}

The following code works. I've made no attemps to optimize anything. Unless the server restricts outgoing connections, you can use this server-side.
protected static string DoRequest()
{
string XML = "<?xml version=\"1.0\"?>"
+"<methodCall>"
+"<methodName>send</methodName>"
+" <params>"
+" <param>"
+ " <value><string>MY KEY</string></value>"
+" </param>"
+" <param>"
+ " <value><string>service#example.com</string></value>"
+" </param>"
+" <param>"
+ " <value><string>555555555</string></value>"
+" </param>"
+" <param>"
+" <value><string>Test Message</string></value>"
+" </param>"
+" </params>"
+"</methodCall>";
return SendText("http://api.pennysms.com/xmlrpc", XML);
}
public static string SendText(string _URL, string _parameters)
{
WebRequest request = WebRequest.Create(_URL);
request.Method = "POST";
string postData = _parameters;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "text/xml";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
long responseLength = request.GetResponse().ContentLength;
Stream responseStream = request.GetResponse().GetResponseStream();
MemoryStream memStream = new MemoryStream((int)responseLength);
byteArray = new byte[4096];
int bytesRead = 0;
bytesRead = responseStream.Read(byteArray, 0, 4096);
while(bytesRead > 0)
{
memStream.Write(byteArray, 0, bytesRead);
bytesRead = responseStream.Read(byteArray, 0, 4096);
}
return Encoding.UTF8.GetString(memStream.ToArray());
}

If you're using the XML-RPC API, have you checked your content-type? It should be "text/xml".

Related

Error:MissingRegistration in GCM with asp.net

I have following code which give "Error:MissingRegistration" response from GCM server.
public void SendPushNotification()
{
string stringregIds = null;
List<string> regIDs = _db.Directories.Where(i => i.GCM != null && i.GCM != "").Select(i => i.GCM).ToList();
//Here I add the registrationID that I used in Method #1 to regIDs
stringregIds = string.Join("\",\"", regIDs);
//To Join the values (if ever there are more than 1) with quotes and commas for the Json format below
try
{
string GoogleAppID = "AIzaSyA2Wkdnp__rBokCmyloMFfENchJQb59tX8";
var SENDER_ID = "925760665756";
var value = "Hello";
WebRequest tRequest;
tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
tRequest.Method = "post";
Request.ContentType = "application/json";
tRequest.Headers.Add(string.Format("Authorization: key={0}", GoogleAppID));
tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));
string postData = "{\"collapse_key\":\"score_update\",\"time_to_live\":108,\"delay_while_idle\":true,\"data\": { \"message\" : " + "\"" + value + "\",\"time\": " + "\"" + System.DateTime.Now.ToString() + "\"},\"registration_ids\":[\"" + stringregIds + "\"]}";
Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
tRequest.ContentLength = byteArray.Length;
Stream dataStream = tRequest.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse tResponse = tRequest.GetResponse();
dataStream = tResponse.GetResponseStream();
StreamReader tReader = new StreamReader(dataStream);
string sResponseFromServer = tReader.ReadToEnd();
TempData["msg1"] = "<script>alert('" + sResponseFromServer + "');</script>";
HttpWebResponse httpResponse = (HttpWebResponse)tResponse;
string statusCode = httpResponse.StatusCode.ToString();
tReader.Close();
dataStream.Close();
tResponse.Close();
}
catch (Exception ex)
{
}
}
But exact string returned by 'postData' posted by Postman or Fiddler gives positive response and notification arrived at device.
What I'm missing in my code please help me.
The postData returns this value which successfully posted by Postman And Fiddler
{"collapse_key":"score_update","time_to_live":108,"delay_while_idle":true,"data": { "message" : "Hello","time": "5/13/2016 5:50:59 PM"},"registration_ids":["cXMf6hkYIrw:APA91bGr-8y2Gy-qzNJ3zjrlf8t-4m9uDib9P0j8GW87bH5jq891-x_7P0qqItzlc_HXh11Arg76lCOcjXPrU9LAgtYLwllH2ySxA0ADSfiz3qPolajjvI3d3zE6Rh77dwRqXn3NnbAm"]}
The problem in your code is in ContentType
Instead of using this:-
Request.ContentType = "application/json";
Use
tRequest.ContentType = "application/json";
It will work
Try This:-
private string SendGCMNotification()
{
try
{
string message = "some test message";
//string tickerText = "example test GCM";
string contentTitle = "content title GCM";
string registration_id = "cXMf6hkYIrw:APA91bGr-8y2Gy-qzNJ3zjrlf8t-4m9uDib9P0j8GW87bH5jq891-x_7P0qqItzlc_HX‌​h11Arg76lCOcjXPrU9LAgtYLwllH2ySxA0ADSfiz3qPolajjvI3d3zE6Rh77dwRqXn3NnbAm";
string postData =
"{ \"registration_ids\": [ \"" + registration_id + "\" ], " +
"\"data\": {\"contentTitle\":\"" + contentTitle + "\", " +
"\"message\": \"" + message + "\"}}";
string GoogleAppID = "AIzaSyA2Wkdnp__rBokCmyloMFfENchJQb59tX8";
WebRequest wRequest;
wRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
wRequest.Method = "POST";
wRequest.ContentType = " application/json;charset=UTF-8";
wRequest.Headers.Add(string.Format("Authorization: key={0}", GoogleAppID));
var bytes = Encoding.UTF8.GetBytes(postData);
wRequest.ContentLength = bytes.Length;
var stream = wRequest.GetRequestStream();
stream.Write(bytes, 0, bytes.Length);
stream.Close();
var wResponse = wRequest.GetResponse();
stream = wResponse.GetResponseStream();
var reader = new StreamReader(stream);
var response = reader.ReadToEnd();
var httpResponse = (HttpWebResponse)wResponse;
var status = httpResponse.StatusCode.ToString();
reader.Close();
stream.Close();
wResponse.Close();
//TODO check status
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return "sent";
}

Unable to Push notification by using GCM in android and C#

I have register my device in GCM, but my push GCM doesn't work. What is wrong with my code?
asp.net side
protected void Button1_Click(object sender, EventArgs e)
{
send("APA91bHwwSLPkdIfqxW8gsosp1J1zgUUsHsgY1LFxetxig4Abo3MfYg7mdbvU3gqLMN5VhW08HvHKhxsHzRAqbRs7WtE6jAQux77XZpx9_1p20O9LMrzpa9mw_RmXoyfq5bkxsLEHO7n6ZGWHzmfzZxaimp46GwR8g");
}
void send(string regId)
{
try
{
var applicationID = "tokyo-***se-***12";
var SENDER_ID = "8500****7538";
var value = "push message";
WebRequest tRequest;
tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
tRequest.Method = "post";
tRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8";
tRequest.Headers.Add(string.Format("Authorization: key={0}", applicationID));
tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));
// string postData = "{ 'registration_id': [ '" + regId + "' ], 'data': {'message': '" + txtMsg.Text + "'}}";
string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message=" + value + "&data.time=" + System.DateTime.Now.ToString() + "&registration_id=" + regId + "";
Console.WriteLine(postData);
Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
tRequest.ContentLength = byteArray.Length;
Stream dataStream = tRequest.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse tResponse = tRequest.GetResponse();
dataStream = tResponse.GetResponseStream();
StreamReader tReader = new StreamReader(dataStream);
String sResponseFromServer = tReader.ReadToEnd();
lblStat.Text = sResponseFromServer;
tReader.Close();
dataStream.Close();
tResponse.Close();
}
catch (Exception w)
{
Response.Write(w.Data);
}
}
web.config
<appSettings >
<add key="GOOGLE_API_KEY" value="AIzaSyCuXwVivtKDKBqS2zxGCrD7Cc2Qwpjxgcw"/>
</appSettings>
It looks like you are sending the wrong authorization key here:
tRequest.Headers.Add(string.Format("Authorization: key={0}", applicationID));
You will need to change applicationID here to your API key, which you assigned to GOOGLE_API_KEY.
Lastly, you may want to consider hiding your actual API key from this StackOverflow post.

save response from web request as mp3 file

When i try to read the stream i get timeout exception. The response i get from the server is the mp3 file and i don't have a clue how to save it as a mp3.
WebClient webClient = new WebClient();
int selectedIndex = listBox2.SelectedIndex;
JObject o = JObject.Parse(result);
string SongID = o["SongID"].ToString();
string SongName = o["SongName"].ToString();
string Year = o["Year"].ToString();
string AlbumName = o["AlbumName"].ToString();
textBox4.Text = SongID + Environment.NewLine + SongName + Environment.NewLine + Year + Environment.NewLine + AlbumName;
string stream = Webpost("{\"header\":{\"token\":\"" +prepToken("getStreamKeyFromSongIDEx", ":chickenFingers:")+"\",\"privacy\":0,\"country\":{\"DMA\":0,\"CC1\":0,\"IPR\":0,\"CC2\":0,\"CC3\":2305843009213694000,\"ID\":190,\"CC4\":0},\"uuid\":\"8E5D1ABD-EE1B-4498-B960-8E46077E8ED4\",\"client\":\"jsqueue\",\"session\":\""+session+"\",\"clientRevision\":\"20130520\"},\"method\":\"getStreamKeyFromSongIDEx\",\"parameters\":{\"mobile\":false,\"prefetch\":false,\"songID\":"+SongID+",\"type\":0,\"country\":{\"DMA\":0,\"CC1\":0,\"IPR\":0,\"CC2\":0,\"CC3\":2305843009213694000,\"ID\":190,\"CC4\":0}}}", "http://*****.com/more.php?getStreamKeyFromSongIDEx", "POST", "text/plain");
JObject ss = JObject.Parse(stream);
string streamkey = ss["result"]["streamKey"].ToString();
string ip = ss["result"]["ip"].ToString();
textBox4.Text += Environment.NewLine+ "downloiad url: " + ip + Environment.NewLine + "stream key: " + streamkey;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://" + ip + "/stream.php");
request.Method = "POST";
string postData = "streamKey="+ streamkey;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentLength = postData.Length;
request.Host = ip;
request.Accept = "*/*";
request.Headers.Add("Origin", string.Format("http://*********.com"));
request.Headers.Add("Accept-Language", string.Format("sv-SE,sv;q=0.8,en-US;q=0.6,en;q=0.4"));
request.Headers.Add("Accept-Encoding", string.Format("gzip,deflate,sdch"));
request.Headers.Add("Cookie", string.Format("ismobile=no; PHPSESSID="+ session + "__utma=111479378.517776767.1385046829.1385170025.1385750338.12; __utmb=111479378.14.9.1385751143490; __utmc=111479378; __utmz=111479378.1385157436.6.2.utmcsr=nettech.wikia.com|utmccn=(referral)|utmcmd=referral|utmcct=/wiki/*****_Internal_API"));
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36";
textBox4.Text += Environment.NewLine + "headers: " + Environment.NewLine + request.Headers;
textBox4.Text += Environment.NewLine + "StreamKey:" + byteArray;
Stream respStream = request.GetRequestStream();
you can try something like this
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("mp3 url");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Get the stream associated with the response.
Stream receiveStream = response.GetResponseStream();
byte[] buffer = new byte[32768];
using (FileStream fileStream = File.Create("yourfullnamepath.mp3"))
{
while (true)
{
int read = receiveStream.Read(buffer, 0, buffer.Length);
if (read <= 0)
break;
fileStream.Write(buffer, 0, read);
}
}

WebRequest and data from label

I created the authorization on PHP-MySql and it works fine. All spoil the TextBox I think. This is my PHP code. No errors in it.
<?php
include('../functions.php'); // connect mysqli
if ($_POST['form_name'] == 'loginform') {
$crypt_pass = md5($_POST['password']);
$found = false;
$res = $mysqli->query("SELECT password FROM accounts WHERE username = '".$mysqli->real_escape_string($_POST['username'])."'");
if ($data = $res->fetch_array()) {
if ($crypt_pass == $data['password']) {
$found = true;
}
}
if ($found == false) {
echo 'LoginFail';
}
else {
echo 'LoginOK';
}
}
?>
And my WebRequest:
WebRequest request = WebRequest.Create("http://unknow.com/user/login2.php");
request.Method = "POST";
string postData = "form_name=loginform&username=" + LoginInput +
"&password=" + PasswordInput;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);
response_label.Text = responseFromServer;
reader.Close();
dataStream.Close();
response.Close();
When this code all right, PHP tell me "LoginOK":
string postData="form_name=loginform&username=snosme&password=123456";
But when code:
string postData = "form_name=loginform&username=" + LoginInput +
"&password=" + PasswordInput;
PHP tell me LoginFail. Although I enter the same data in the TextBox. What's the problem?
After seeing your image, I think the problem is that you are forgetting to get the Text value in the text field. Try this:
string postData = "form_name=loginform&username=" + LoginInput.Text +
"&password=" + PasswordInput.Text;

Send tile notification - windows phone

Helo,
I want to ask you, if I can send tile notification from one phone to another phone and vice versa using WCF service?
Thanks
To send push to other phone you have to have ChannelURI. There is good article about it
http://msdn.microsoft.com/en-us/library/hh221549.aspx
When you have this adress you have to send special XML data
string textTitle = tbxTitle.Text;
string textSubtitle = tbxSubtitle.Text;
string deviceUri = tbxUri.Text;
string msg =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<wp:Notification xmlns:wp=\"WPNotification\">" +
"<wp:Toast>" +
"<wp:Text1>" + textTitle + "</wp:Text1>" +
"<wp:Text2>" + textSubtitle + "</wp:Text2>" +
"</wp:Toast>" +
"</wp:Notification>";
byte[] msgBytes = new UTF8Encoding().GetBytes(msg);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(channelUri);
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "text/xml";
request.ContentLength = msg.Length;
request.Headers["X-MessageID"] = Guid.NewGuid().ToString();
request.Headers["X-WindowsPhone-Target"] = "toast";
request.Headers["X-NotificationClass"] = "2";
Stream requestStream = request.GetRequestStream();
requestStream.Write(msgBytes, 0, msgBytes.Length);
requestStream.Close();

Categories