I get the tokenUpdate from the device, and then I try to send a push notification. But I don't think that it is working as when I send a push notification, I do not get any response from the device. Isn't it suppose to poll the server to check for any MDM Commands? Instead I keep receiving token update.
String cToken = token;
String cAlert = message;
// Ready to create the push notification
byte[] buf = new byte[256];
MemoryStream ms = new MemoryStream();
BinaryWriter bw = new BinaryWriter(ms);
char[] tokenChars = token.ToCharArray();
byte[] deviceTokenBytes = new byte[tokenChars.Length];
for (int i=0; i < deviceTokenBytes.Length; i++)
{
deviceTokenBytes[i] = Convert.ToByte(tokenChars[i]);
}
// byte[] deviceToken = HexToData(cToken);
bw.Write(deviceTokenBytes);
// Create the APNS payload - new.caf is an audio file saved in the application bundle on the device
//string msg = "{\"aps\":{\"alert\":\"" + cAlert + "\",\"badge\":" + iBadge.ToString() + ",\"sound\":\"new.caf\"}}";
string msg = "{\"mdm\":\"+ mPushMagic +"\"}";
// Write the data out to the stream
// bw.Write((byte)msg.Length);
bw.Write(msg.ToCharArray());
bw.Flush();
if (sslStream != null)
{
sslStream.Write(ms.ToArray());
return true;
}
return false;
}
UPDATED: I removed the '<' from the pushmagic id
I'd recommend removing the chevrons from your mdm message to start with.
Related
I know this question have been ask a lot of time in android but not ios. So I already test out push notification with FCM it work fine. Mine problem is wether it's a way to create custom notification rather than letting the system to handle the notification with the notification payload?
-Users can send data messages with FCM.What you have to send is,
Sample PostMan Json data:
{ "data": {
"any key": "any value",
"any key 2": "any value 2"
},
"to" : "token received to mobile from FCM"
}
Payload inside "data" can change according to the requirement.
Mobile end:
application(_:didReceiveRemoteNotification:) override method will get fire.So it is unto developer to extract data from the userInfo property in iOS and use it.
For ios using c# working code:-
public bool NotificationToiosDevice()
{
bool str;
try
{
//Create the web request with fire base API
WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
tRequest.Method = "post";
//serverKey - Key from Firebase cloud messaging server
tRequest.Headers.Add(string.Format("Authorization: key={0}", "AAAALNl-P7o:APA91bE38khU73UTdIj7L6LvVS3uI6f47REmxl.................................."));
//Sender Id - From firebase project setting
tRequest.Headers.Add(string.Format("Sender: id={0}", "12345"));
tRequest.ContentType = "application/json";
var payload = new
{
to = "dDDbFltwE5o:APA91bFmZZ-c1pNp................",
priority = "high",
content_available = true,
notification = new
{
title = "Title Of Notification",
},
data = new
{
body = new { Parameter1 = "FirstParameterValue", Parameter2 = "SecondParameterValue" },
},
};
string jsonNotificationFormat = Newtonsoft.Json.JsonConvert.SerializeObject(payload);
Byte[] byteArray = Encoding.UTF8.GetBytes(jsonNotificationFormat);
tRequest.ContentLength = byteArray.Length;
using (Stream dataStream = tRequest.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
using (WebResponse tResponse = tRequest.GetResponse())
{
using (Stream dataStreamResponse = tResponse.GetResponseStream())
{
if (dataStreamResponse != null) using (StreamReader tReader = new StreamReader(dataStreamResponse))
{
String sResponseFromServer = tReader.ReadToEnd();
// str = sResponseFromServer;
}
}
}
}
str = true;
}
catch (Exception ex)
{
str = false;
}
return str;
}
If I send notification to iOS device from FCM console I am getting the message alert on notification center (swipe down from the Top of the screen to view Notification Centre).
didRecievedRemoteNotification Output is :
{
aps = {
alert = "From console";
};
"gcm.message_id" = "0:1470206236110595%b2c76869b2c76869";
"gcm.n.e" = 1;
"google.c.a.c_id" = 2979094970349938289;
"google.c.a.e" = 1;
"google.c.a.ts" = 1470206236;
"google.c.a.udt" = 0;
}
But if send notification to iOS device I am sending using api from my server I am not receiving message alert on notification center (swipe down from the Top of the screen to view Notification Centre).
didRecievedRemoteNotification Output is :
{
"collapse_key" = "do_not_collapse";
from = 67981113117;
message = "alert from api";
time = "03-08-2016 12:44:53";
}
My API code is which is in C#:
string RegIDs = "some id";
var appID = "some id";
var SenderID = "some id";
var value = Text1.Text;
WebRequest tRequest;
tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
tRequest.Method = "POST";
tRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
tRequest.Headers.Add(string.Format("Authorization: key={0}", appID));
tRequest.Headers.Add(string.Format("Sender: id={0}", SenderID));
//Data_Post Format
// string postData = "{'collapse_key' : 'demo', 'registration_id': [ '" + regId + "' ],
//'data': {'message': '" + Label1.Text + "'},'time_to_live' : '3' }";
//json for android
string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message="
+ value + "&data.time=" + System.DateTime.Now.ToString() + "®istration_id=" + RegIDs + "";
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 = (WebResponse)tRequest.GetResponse();
dataStream = tResponse.GetResponseStream();
StreamReader tReader = new StreamReader(dataStream);
String sResponseFromServer = tReader.ReadToEnd();
Label3.Text = sResponseFromServer; //printing response from GCM server.
tReader.Close();
dataStream.Close();
tResponse.Close();
Another alternative in order to test push notifications without using Firebase console is using Postman. Attached two images with configuration details.
Image 1: Set notification payload
Image 2: Set request headers ( Content-Type and Authorization )
Firebase push notification endpoint: https://fcm.googleapis.com/fcm/send
I am using the below code for push notification.
public void PushNotificationIOS(string message, string registrationKey)
{
string deviceID = registrationKey;
int port = 2195;
String hostname = System.Configuration.ConfigurationManager.AppSettings["HostName"];//"gateway.sandbox.push.apple.com";
string certPath = string.Empty;
certPath = System.Configuration.ConfigurationManager.AppSettings["CertificatePath"] + System.Configuration.ConfigurationManager.AppSettings["Cer
String certificatePath = System.Web.HttpContext.Current.Server.MapPath(certPath);
string certPassword = System.Configuration.ConfigurationManager.AppSettings["CertificatePassword"];
TcpClient client = new TcpClient(hostname, port);
try
{
X509Certificate2 clientCertificate = new X509Certificate2(System.IO.File.ReadAllBytes(certificatePath), certPassword);
X509Certificate2Collection certificatesCollection = new X509Certificate2Collection(clientCertificate);
SslStream sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
sslStream.AuthenticateAsClient(hostname, certificatesCollection, SslProtocols.Tls, false);
MemoryStream memoryStream = new MemoryStream();
BinaryWriter writer = new BinaryWriter(memoryStream);
writer.Write((byte)0);
writer.Write((byte)0);
writer.Write((byte)32);
writer.Write(StringToByteArray(deviceID.ToUpper()));
String payload = "{\"aps\":{\"alert\":\"" + message + "\",\"badge\":0,\"sound\":\"default\"}}";
writer.Write((byte)0);
writer.Write((byte)payload.Length);
byte[] b1 = System.Text.Encoding.UTF8.GetBytes(payload);
writer.Write(b1);
writer.Flush();
byte[] array = memoryStream.ToArray();
sslStream.Write(array);
sslStream.Flush();
client.Close();
}
catch (System.Security.Authentication.AuthenticationException ex)
{
client.Close();
}
}
I am getting the following error
Authentication failed because the remote party has closed the transport stream.
On Trace, I am getting the below
System.Net.Security.SslState.CheckThrow(Boolean authSucessCheck)
at System.Net.Security.SslState.get_SecureStream()
at System.Net.Security.SslStream.Write(Byte[] buffer)
I tried all the things mentioned in various post but am not able to solve the issue.
Make sure certificate is valid & is not corrupted. You can regenerate certificate to be dead sure.
Try providing all the options for SecurityProtocolType like :
sslStream.AuthenticateAsClient(hostname, certificatesCollection, SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls, false);
SecurityProtocolType.Tls12 can negotiate Transport layer security 1.1 or downwards too but try all options to be sure.
For more details on SecurityProtocolType refer :
https://msdn.microsoft.com/en-us/library/system.net.securityprotocoltype(v=vs.110).aspx
I have an asp.net MVC application, below code works file.
But the code is that, When navigate to Email action in browser, an EML file is download, then when we click on that file, the file will open with outlook.
Can it be possible, when action calls, then EML file will directly open with outlook, instead of download and then click to open??
Code
public async Task<FileStreamResult> Email()
{
string dummyEmail = "test#localhost.com";
var mailMessage = new MailMessage();
mailMessage.From = new MailAddress(dummyEmail);
mailMessage.To.Add("dejan.caric#gmail.com");
mailMessage.Subject = "Test subject";
mailMessage.Body = "Test body";
// mark as draft
mailMessage.Headers.Add("X-Unsent", "1");
// download image and save it as attachment
using (var httpClient = new HttpClient())
{
var imageStream = await httpClient.GetStreamAsync(new Uri("http://dcaric.com/favicon.ico"));
mailMessage.Attachments.Add(new Attachment(imageStream, "favicon.ico"));
}
var stream = new MemoryStream();
ToEmlStream(mailMessage, stream, dummyEmail);
stream.Position = 0;
return File(stream, "message/rfc822", "test_email.eml");
}
private void ToEmlStream(MailMessage msg, Stream str, string dummyEmail)
{
using (var client = new SmtpClient())
{
var id = Guid.NewGuid();
var tempFolder = Path.Combine(Path.GetTempPath(), Assembly.GetExecutingAssembly().GetName().Name);
tempFolder = Path.Combine(tempFolder, "MailMessageToEMLTemp");
// create a temp folder to hold just this .eml file so that we can find it easily.
tempFolder = Path.Combine(tempFolder, id.ToString());
if (!Directory.Exists(tempFolder))
{
Directory.CreateDirectory(tempFolder);
}
client.UseDefaultCredentials = true;
client.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
client.PickupDirectoryLocation = tempFolder;
client.Send(msg);
// tempFolder should contain 1 eml file
var filePath = Directory.GetFiles(tempFolder).Single();
// create new file and remove all lines that start with 'X-Sender:' or 'From:'
string newFile = Path.Combine(tempFolder, "modified.eml");
using (var sr = new StreamReader(filePath))
{
using (var sw = new StreamWriter(newFile))
{
string line;
while ((line = sr.ReadLine()) != null)
{
if (!line.StartsWith("X-Sender:") &&
!line.StartsWith("From:") &&
// dummy email which is used if receiver address is empty
!line.StartsWith("X-Receiver: " + dummyEmail) &&
// dummy email which is used if receiver address is empty
!line.StartsWith("To: " + dummyEmail))
{
sw.WriteLine(line);
}
}
}
}
// stream out the contents
using (var fs = new FileStream(newFile, FileMode.Open))
{
fs.CopyTo(str);
}
}
}
With Chrome you can make it automatically open certain files, once they are downloaded.
.EML should attempt to open in Outlook.
I am not sure about other browsers, but Chrome seemed to be the only one with this option.
It's not a pefect solution because if someone downloaded an .EML from another website in Chrome, it will open automatically aswell.
I recommend having Chrome dedicated to your Web application.
You sure can open local .eml file with Outlook.
But in context of web application, you must firstly download it.
I am quite new to blackberry application development and i need to create an application which can receive push notifications.
I have created the application and was trying to use xtify for pushing notifications to devices.
I have registered with rim for the push evaluation and got the credentials like url,app id,password etc.
When the application launches , i create a new thread to perform the push registration process.
I try to send an http Get request to the push evaluation url for registering the device.When i try to open a connection,i get the io exception,invalid url parameter.
I am using a wifi connection for network connectivity in device. I donot have a sim in the device.
The url is
http://cpXXX.pushapi.eval.blackberry.com/mss/PD_subReg?serviceid='My Application Id'&osversion='My OS Version'&model='Device Model';deviceside=false;ConnectionType=mds-public
Below is the code i use to send the request.
DataBuffer buffer = new DataBuffer(256, false);
httpUrl = "http://cpXXX.pushapi.eval.blackberry.com/mss/PD_subReg?serviceid='My Application Id'&osversion='My OS Version'&model='Device Model';deviceside=false;ConnectionType=mds-public"
InputStream inputStream = null;
Connection conn = null;
HttpConnection httpConn = null;
try {
httpUrl ;
conn = Connector.open(httpUrl);
if (conn instanceof HttpConnection) {
httpConn = (HttpConnection) conn;
int responseCode = httpConn.getResponseCode();
if(responseCode == 200){
inputStream = httpConn.openInputStream();
int length = inputStream.read(buffer.getArray());
buffer.setLength(length);
String response = new String( buffer.getArray(), buffer.getArrayStart(), buffer.getArrayLength() );
return response;
}else {
throw new IOException( "Http error: " + responseCode);
}
}
else {
throw new IOException("Can not make HTTP connection for URL '"
+ httpUrl + "'");
}
}
finally {
if (httpConn != null) {
try {
httpConn.close();
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
close(conn, inputStream, null);
}
Please help me. I am waiting for replies. I have been stuck with this for days. Please advice. Anyone have idea where i can get a documentation for the device registration api ??
Thanx to the advice of #Black Pearl , I was able to resolve the issue. Inorder for the blackberry registration to work , you need an active BIS connection. I had been trying it with wifi connectivity and hence it was not working.