I want to read the iOS push "alert" message
parse.com has this example on their website
ParsePush.ParsePushNotificationReceived += (sender, args) => {
var payload = args.Payload;
object objectId;
if (payload.TryGetValue("objectId", out objectId)) {
DisplayRichMessageWithObjectId(objectId as string);
}
};
But how do I read the alert message from the payload?
Solution
string message = "";
try
{
var payload = args.Payload;
object aps;
if (payload.TryGetValue("aps", out aps))
{
string payloadStr = "";
try
{
payloadStr = aps.ToString();
}
catch (Exception e)
{
}
try
{
var match = Regex.Match(payloadStr, #"alert = (.*);\n");
if (match.Success)
{
string alertText = match.Groups[1].Value;
message = alertText;
}
}
catch (Exception)
{
}
}
}
Try this:
ParsePush.ParsePushNotificationReceived += (sender, args) => {
var payload = args.Payload;
object aps;
if (payload.TryGetValue("aps", out aps)) {
string payloadStr = aps as string;
}
};
Also, there should be a args.PayloadString which should give some clues about the structure of the payload.
Related
NDesk doesn't throw exceptions while parsing args. When I do debug without any arguments, the next step after try is the if and not the catch section. Any suggestions?
My code is:
using System;
using System.Collections.Generic;
using NDesk.Options;
namespace test
{
internal class Program
{
private static void Main(string[] args)
{
string emailFrom = "";
string emailTo = "";
string emailSubject = "";
string emailBody = "";
bool showHelp = false;
var p = new OptionSet()
{
{ "f|from", "email to send from", v => emailFrom = v },
{ "t|to", "email to send to", v => emailTo = v },
{ "s|subject", "subject of email", v => emailSubject = v },
{ "b|body", "body of email", v => emailBody= v },
{ "h|help", "show this help and exit", v => showHelp = v != null }
};
List<string> extra;
try
{
extra = p.Parse(args);
}
catch (OptionException e)
{
Console.WriteLine(e.Message);
Console.WriteLine("Try `{0} --help` for more information.", projectName);
return;
}
if (showHelp)
{
ShowHelp(p);
return;
}
Console.WriteLine("Done");
}
private static void ShowHelp(OptionSet p)
{
// show help
}
}
}
I am following the documentation here:
http://ndesk.org/doc/ndesk-options/NDesk.Options/OptionSet.html.
I am trying to get all messages id from my email,but it doesn't work. I get this answer:
$ BAD [CLIENTBUG] Unrecognised command\r\n\0\0\0\0.
How do I get the correct response?
string uids1 = ReceiveResponse("$ SELECT INBOX\r\n");
string uids = ReceiveResponse("$ UID SEARCH ALL" + "\r\n");//query to server
private string ReceiveResponse(string command)
{
_sb = new StringBuilder();
try
{
if (command != "")
{
if (_tcpClient.Connected)
{
_dummy = Encoding.ASCII.GetBytes(command);
_ssl.Write(_dummy, 0, _dummy.Length);
}
else
{
throw new ApplicationException("TCP CONNECTION DISCONNECTED");
}
}
_ssl.Flush();
_buffer = new byte[2048];
_tcpClient.ReceiveTimeout = 20000;
Encoding iso = Encoding.GetEncoding("ISO-8859-1");
do
{
try
{
bytes = _ssl.Read(_buffer, 0, 2048);
var msg = Encoding.UTF8.GetString(_buffer);
_sb.Append(msg);
Thread.Sleep(3);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
} while (_tcpClient.Available > 0);
string text = _sb.ToString().Replace("\0", string.Empty);
return _sb.ToString();
}
catch (Exception ex)//if we have some problem show message
{
throw new ApplicationException(ex.Message);
}
}
I'm writing a function which creates a Process and runs it.
Here is the original function:
public static void LaunchApplication(string runCommand, string commandArguments, string workingDir, string informMessage)
{
try
{
Process applicationProcess = new Process();
applicationProcess.StartInfo.FileName = runCommand;
applicationProcess.StartInfo.WorkingDirectory = workingDir;
applicationProcess.StartInfo.Arguments = commandArguments;
applicationProcess.StartInfo.UseShellExecute = false;
WriteHeadlineToConsole(informMessage);
applicationProcess.Start();
while (Process.GetProcesses().Any(runningProcess => runningProcess.Id == applicationProcess.Id)) { }
WriteHeadlineToConsole("Finished " + informMessage);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return;
}
}
I would like to change the functions' signature to something like:
public static void LaunchApplication(string runCommand, string commandArguments, string workingDir, string informMessage, Func<object, DataReceivedEventArgs> myMethodName)
And then inside the function, redirect the output, something like:
applicationProcess.OutputDataReceived += new DataReceivedEventHandler(myMethodName);
Can this be done?
Try this:
public static void LaunchApplication(string runCommand, string commandArguments, string workingDir, string informMessage, Action<string> redirectOutput, Action<string> redirectError)
{
try
{
Process applicationProcess = new Process();
applicationProcess.StartInfo.FileName = runCommand;
applicationProcess.StartInfo.WorkingDirectory = workingDir;
applicationProcess.StartInfo.Arguments = commandArguments;
applicationProcess.StartInfo.UseShellExecute = false;
applicationProcess.EnableRaisingEvents = true;
applicationProcess.StartInfo.CreateNoWindow = true;
if (redirectOutput != null)
applicationProcess.OutputDataReceived += (s, data) => redirectOutput(data.Data);
if (redirectError != null)
applicationProcess.ErrorDataReceived += (sErr, errData) => redirectError(errData.Data);
GeneralUtils.WriteHeadlineToConsole(informMessage);
applicationProcess.Start();
if (redirectOutput != null)
applicationProcess.BeginOutputReadLine();
if (redirectError != null)
applicationProcess.BeginErrorReadLine();
applicationProcess.WaitForExit();
GeneralUtils.WriteHeadlineToConsole("Finished " + informMessage);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return;
}
}
Usage:
LaunchApplication("cmd.exe", "/C ipconfig /all", "C:\\Windows", "Test",
s => Console.WriteLine("HELLO: " + s));
PS:
The following code is awful! AccessDeniedException might be thrown, CPU is going crazy!
while (Process.GetProcesses().Any(runningProcess => runningProcess.Id == applicationProcess.Id)) { }
Use applicationProcess.WaitForExit(); instead!
I'm issue when I get +CDS in AT COMMAND throught c# using SerialPort, any times I get this +CDS truncated, example:
+CDS: 25
0002970C91555868047414212181414094882121814140948830
Why I've this problem, why any times work nice?
I'm starting SerialPort:
public PortCOM(string porta)
: base(porta, 115200, Parity.None, 8, StopBits.One)
{
this.StatusPort = StatusPorta.Ready;
this.DiscardNull = true;
this.ReadTimeout = 21000;
this.RtsEnable = true;
this.DtrEnable = true;
this.ReceivedBytesThreshold = 9;
this.NewLine = "\r\n";
this.ReadBufferSize = 1024;
}
public static void TestPort()
{
var p = new PortCom("COM12");
if (!p.IsOpen)
p.Open();
p.StatusPort = StatusPorta.Ready;
p.DataReceived += new SerialDataReceivedEventHandler(p_DataReceivedSample);
p.PinChanged += new SerialPinChangedEventHandler(p_PinChanged);
p.ErrorReceived += new SerialErrorReceivedEventHandler(p_ErrorReceived);
p.Disposed += new EventHandler((obj, porta) =>
{
Console.WriteLine(((PortaCOM)obj).ToString());
});
if (Console.ReadKey().Key == ConsoleKey.B)
{
p.Close();
p.Dispose();
}
}
static void p_DataReceivedSample(object sender, SerialDataReceivedEventArgs e)
{
var p = (PortaCOM)sender;
try
{
Console.WriteLine(p.ReadExisting());
var sb = new StringBuilder();
sb.Append(p.ReadExisting());
int y = sb.ToString().IndexOf("\r\n");
var stop = Stopwatch.StartNew();
stop.Start();
while (y == -1)
{
sb.Append(p.ReadExisting());
y = sb.ToString().IndexOf("\r\n");
if (stop.Elapsed.TotalSeconds > 10)
break;
}
stop.Stop();
var _retorno = sb.ToString();
var cmt = regCMT.Match(_retorno);
var succ = regSucess.Match(_retorno);
var report = regStatusReport.Match(_retorno);
var erro = regError.Match(_retorno);
#region Resposta
if (cmt.Success)
{
var smss = new SMS();
var source = cmt.Groups[3].Value;
SMS.Fetch(smss, ref source);
var resposta = new Resposta()
{
Mensagem = smss.Message,
Data = smss.ServiceCenterTimeStamp,
Sender = smss.PhoneNumber,
Operadora = p.OperadoraName.NomeOperadora.ToString()
};
GravaResposta().ToAsync(Scheduler.TaskPool).Invoke(p, cmt.Groups[3].Value);
p.IsError = false;
}
#endregion
#region StatusReport
if (report.Success)
{
RecebeReport(p, report.Groups[2].Value.Trim());
p.IsError = false;
}
#endregion
}
catch (Exception err)
{
Console.WriteLine(err.Message);
}
}
Please I really need help with it, I'm glad for any help!
+cds is alert for incoming message with message location on SIM memeory.
so here its seems in PDU mode data. and it is seems may be flash message content.
Convert the data PDU mode to Text mode to receive message.
review this ATSMS library
This code is showing the address on a google maps sending the address text to an url and then retrieving it in a Json object, Is there a way to transalate this code to Monodroid using Httppost from apache libraries or not?
public class MapsActivity extends MapActivity {
Geocoder geocoder = null;
MapView mapView = null;
ProgressDialog progDialog = null;
List<Address> addressList = null;
double latitude;
double longitude;
#Override
protected boolean isRouteDisplayed() {
return false;
}
#Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
mapView = (MapView) findViewById(R.id.geoMap);
progDialog = ProgressDialog.show(MapsActivity.this, "Processing...",
"Finding Location...", true, false);
TextView txtAddress = (TextView)findViewById(R.id.location);
String locationName = "Av. Venezuela 1234 Lima Peru";
txtAddress.setText(locationName);
JSONObject location = getLocationInfo(locationName);
Boolean bool = getLatLong(location);
if(location!=null && bool != false){
int lat = (int) (latitude * 1000000);
int lng = (int) (longitude * 1000000);
GeoPoint pt = new GeoPoint(lat, lng);
mapView.getController().setZoom(16);
mapView.getController().setCenter(pt);
mapView.getController().animateTo(pt);
}else {
Dialog foundNothingDlg = new AlertDialog.Builder(
MapsActivity.this).setIcon(0)
.setTitle("Failed to Find Location")
.setPositiveButton("Ok", null)
.setMessage("Location Not Found...").create();
foundNothingDlg.show();
}
}
public JSONObject getLocationInfo(String address) {
StringBuilder stringBuilder = new StringBuilder();
try {
address = address.replaceAll(" ","%20");
HttpPost httppost = new HttpPost("http://maps.google.com/maps/api/geocode/json?address=" + address + "&sensor=false");
HttpClient client = new DefaultHttpClient();
HttpResponse response;
response = client.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
JSONObject jsonObject = new JSONObject();
try {
jsonObject = new JSONObject(stringBuilder.toString());
Log.i("JSONOBJECT: ", stringBuilder.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonObject;
}
public boolean getLatLong(JSONObject jsonObject) {
try {
longitude = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
.getJSONObject("geometry").getJSONObject("location")
.getDouble("lng");
latitude = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
.getJSONObject("geometry").getJSONObject("location")
.getDouble("lat");
} catch (JSONException e) {
return false;
}
progDialog.dismiss();
return true;
}
}
HttpPost isn't bound, and it's currently very hard to bind your own Java libraries.
The easiest way to do this would be to use the equivalent .NET classes, like HttpWebRequest or WebClient.