i have developed code for push notification in ios in c# but it is not sending notification in mobile.
I have used pushsharp library.
My code is as followed:
PushNotificationApple pushNotification = new PushNotificationApple();
pushNotification.SendNotification(postData);
My PushNotificationApple constructor code is as below:-
public PushNotificationApple()
{
if (_pushBroker == null)
{
//Create our push services broker
_pushBroker = new PushBroker();
//Wire up the events for all the services that the broker registers
_pushBroker.OnNotificationSent += NotificationSent;
_pushBroker.OnChannelException += ChannelException;
_pushBroker.OnServiceException += ServiceException;
_pushBroker.OnNotificationFailed += NotificationFailed;
_pushBroker.OnDeviceSubscriptionExpired += DeviceSubscriptionExpired;
_pushBroker.OnDeviceSubscriptionChanged += DeviceSubscriptionChanged;
_pushBroker.OnChannelCreated += ChannelCreated;
_pushBroker.OnChannelDestroyed += ChannelDestroyed;
var appleCert = File.ReadAllBytes(System.Web.Hosting.HostingEnvironment.MapPath("~/Certificates" + ConfigSettings.SnaptymAPNSCertificate));
_pushBroker.RegisterAppleService(new ApplePushChannelSettings(false, appleCert,ConfigSettings.SnaptymAPNSPassword)); //Extension method
}
}
My SendNotification function is as below:-
public bool SendNotification(GcmNotificationPostDataModel postData)
{
if (_pushBroker != null)
{
foreach (var registrationId in postData.RegistrationIds)
{
_pushBroker.QueueNotification(new AppleNotification()
.ForDeviceToken(registrationId) //the recipient device id
.WithAlert(postData.Data.Message) //the message
.WithBadge(1)
.WithSound("sound.caf"));
}
}
return true;
}
I am making use of PushSharp 4.0.10 and the following code works for me.
private void SendMessage()
{
//IOS
var MainApnsData = new JObject();
var ApnsData = new JObject();
var data = new JObject();
MainApnsData.Add("alert", Message.Text.Trim());
MainApnsData.Add("badge", 1);
MainApnsData.Add("Sound", "default");
data.Add("aps", MainApnsData);
ApnsData.Add("CalledFromNotify", txtboxID.Text.Trim());
data.Add("CustomNotify", ApnsData);
//read the .p12 certificate file
byte[] bdata = System.IO.File.ReadAllBytes(Server.MapPath("~/App_Data/CertificatesPushNew.p12"));
//create push sharp APNS configuration
var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Sandbox,bdata,"YourPassword");
//create a apnService broker
var apnsBroker = new ApnsServiceBroker(config);
// Wire up events
apnsBroker.OnNotificationFailed += (notification, aggregateEx) => {
aggregateEx.Handle(ex => {
// See what kind of exception it was to further diagnose
if (ex is ApnsNotificationException)
{
var notificationException = (ApnsNotificationException)ex;
// Deal with the failed notification
var apnsNotification = notificationException.Notification;
var statusCode = notificationException.ErrorStatusCode;
Console.WriteLine($"Apple Notification Failed: ID={apnsNotification.Identifier}, Code={statusCode}");
}
else
{
// Inner exception might hold more useful information like an ApnsConnectionException
Console.WriteLine($"Apple Notification Failed for some unknown reason : {ex.InnerException}");
}
// Mark it as handled
return true;
});
};
apnsBroker.OnNotificationSucceeded += (notification) => {
Console.WriteLine("Apple Notification Sent!");
};
var fbs = new FeedbackService(config);
fbs.FeedbackReceived += (string deviceToken1, DateTime timestamp) =>
{
//Remove the deviceToken from your database
// timestamp is the time the token was reported as expired
Console.WriteLine("Feedback received!");
};
fbs.Check();
// Start the broker
apnsBroker.Start();
var deviceToken = "Your device token";
// Queue a notification to send
apnsBroker.QueueNotification(new ApnsNotification
{
DeviceToken = deviceToken,
Payload= data
});
// Stop the broker, wait for it to finish
// This isn't done after every message, but after you're
// done with the broker
apnsBroker.Stop();
}
Related
I'm trying to send iOS push notifications, but the code I'm using is not working due to the events OnNotificationSucceeded and OnNotificationFailed are not triggered.
My code is:
string p12fileName = "path to my iOS push certificate";
string p12password = "my iOS push certificate password";
string deviceToken = "my device ID";
var appleCert = File.ReadAllBytes(p12fileName);
var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Production, appleCert, p12password);
config.ValidateServerCertificate = false;
var apnsBroker = new ApnsServiceBroker(config);
apnsBroker.OnNotificationFailed += (notification, aggregateEx) => {
aggregateEx.Handle(ex => {
// See what kind of exception it was to further diagnose
if (ex is ApnsNotificationException)
{
var notificationException = (ApnsNotificationException)ex;
// Deal with the failed notification
var apnsNotification = notificationException.Notification;
var statusCode = notificationException.ErrorStatusCode;
Response.Write("Apple Notification Failed: ID={" + apnsNotification.Identifier + "}, Code={" + statusCode + "}");
}
else
{
// Inner exception might hold more useful information like an ApnsConnectionException
Response.Write("Notification Failed for some unknown reason : {" + ex.InnerException + "}");
}
// Mark it as handled
return true;
});
};
apnsBroker.OnNotificationSucceeded += (notification) => {
LogDao.Info(deviceData.UserId, "Apple Notification Sent!");
};
SureAct.Helpers.LiteralsHelper literals = new SureAct.Helpers.LiteralsHelper(1, 0);
string message = "test";
apnsBroker.Start();
apnsBroker.QueueNotification(new ApnsNotification
{
DeviceToken = deviceToken,
Payload = JObject.Parse("{\"aps\":{\"alert\":\"" + message + "\",\"badge\":1,\"sound\":\"default\"}}")
});
apnsBroker.Stop();
I checked the certificate and password and they are correct. And If I try to send a push notification using the webpage pushtry.com I receive the push.
What I'm doing wrong? Why the events are not triggered?
Kind regards
I created an console app with .NET 4.0 like this:
static void Test2(string deviceToken, string message)
{
try
{
//Get Certificate
var appleCert = System.IO.File.ReadAllBytes("Certificates_moi.p12");
// Configuration (NOTE: .pfx can also be used here)
var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Sandbox, appleCert, "vnpt1234");
// Create a new broker
var apnsBroker = new ApnsServiceBroker(config);
// Wire up events
apnsBroker.OnNotificationFailed += (notification, aggregateEx) =>
{
aggregateEx.Handle(ex =>
{
// See what kind of exception it was to further diagnose
if (ex is ApnsNotificationException)
{
var notificationException = (ApnsNotificationException)ex;
// Deal with the failed notification
var apnsNotification = notificationException.Notification;
var statusCode = notificationException.ErrorStatusCode;
string desc = "Apple Notification Failed: ID={apnsNotification.Identifier}, Code={statusCode}";
Console.WriteLine(desc);
//lblStatus.Text = desc;
}
else
{
string desc = "Apple Notification Failed for some unknown reason : {ex.InnerException}";
// Inner exception might hold more useful information like an ApnsConnectionException
Console.WriteLine(desc);
//lblStatus.Text = desc;
}
// Mark it as handled
return true;
});
};
apnsBroker.OnNotificationSucceeded += (notification) =>
{
//lblStatus.Text = "Apple Notification Sent successfully!";
Console.WriteLine("Apple Notification Sent successfully!");
};
var fbs = new FeedbackService(config);
fbs.FeedbackReceived += (string devicToken, DateTime timestamp) =>
{
// Remove the deviceToken from your database
// timestamp is the time the token was reported as expired
};
// Start Proccess
apnsBroker.Start();
if (deviceToken != "")
{
apnsBroker.QueueNotification(new ApnsNotification
{
DeviceToken = deviceToken,
Payload = JObject.Parse(("{\"aps\":{\"badge\":1,\"sound\":\"oven.caf\",\"alert\":\"" + (message + "\"}}")))
});
}
apnsBroker.Stop();
}
catch (Exception ex)
{
throw;
}
}
There is an error at apnsBroker.Start();
- $exception {"Specified argument was out of the range of valid values.\r\nParameter name: creationOptions"} System.Exception {System.ArgumentOutOfRangeException}
Can anybody help me, please?
I fixed this issue. Move to another machine running .NET 4.5 and it worked.
I am android app developer .Now, I am developing app for windows phone . I am integrating push notification in windows phone first time by Azure notification Hub. I want help for notification Hub. How to integrate? How to send notification to selected device not to all?
I was integrated notification but after some time notification is stop. I have done with many notification hub credentials. Now notification is coming.
private async void Application_Launching(object sender, LaunchingEventArgs e)
{
StorageFile MyDBFile = null;
try
{
// Read the db file from DB path
MyDBFile = await StorageFile.GetFileFromPathAsync(DB_PATH);
}
catch (FileNotFoundException)
{
if (MyDBFile == null)
{
// Copy file from installation folder to local folder.
IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication();
// Create a stream for the file in the installation folder.
using (Stream input = Application.GetResourceStream(new Uri(DbConst.DATABASE, UriKind.Relative)).Stream)
{
// Create a stream for the new file in the local folder.
using (IsolatedStorageFileStream output = iso.CreateFile(DB_PATH))
{
// Initialize the buffer.
byte[] readBuffer = new byte[4096];
int bytesRead = -1;
// Copy the file from the installation folder to the local folder.
while ((bytesRead = input.Read(readBuffer, 0, readBuffer.Length)) > 0)
{
output.Write(readBuffer, 0, bytesRead);
}
}
}
}
}
var channel = HttpNotificationChannel.Find("MyPushChannel");
if (channel == null)
{
channel = new HttpNotificationChannel("MyPushChannel");
channel.Open();
channel.BindToShellToast();
}
channel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(async (o, args) =>
{
//var hub = new NotificationHub("<hub name>", "<connection string>");
var hub = new NotificationHub("mnokhgjhjhjbohkjkl", "Endpoint=sb://connect-hub.servicebus.windows.net/;SharedAccessKeyName=DefaultListenSharedAccessSignature;SharedAccessKey=RM6jjnbjnbjAnjhttD4yxqnknknklmkmnkkmkkkmmkbnl5rSk=");
Registration x= await hub.RegisterNativeAsync(args.ChannelUri.ToString());
//mChennelURI = x.ChannelUri;
Debug.WriteLine("Chennel URI: " + x.ChannelUri);
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
System.Diagnostics.Debug.WriteLine(args.ChannelUri.ToString());
});
});
channel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(async (o,args) =>
{
// Error handling logic for your particular application would be here.
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
// Show the notification since toasts aren't
// displayed when the app is currently running.
MessageBox.Show(String.Format("A push notification {0} error occurred. {1} ({2}) {3}", args.ErrorType, args.Message, args.ErrorCode,args.ErrorAdditionalData));
});
});
// Handle the event that is raised when a toast is received.
channel.ShellToastNotificationReceived +=new EventHandler<NotificationEventArgs>((o, args) =>
{
string message = "";
foreach (string key in args.Collection.Keys)
{
message += args.Collection[key] + ": ";
}
//string[] separators = { "#"};
// string[] words = message.Split(separators, StringSplitOptions.RemoveEmptyEntries);
// string type = words[0];
// string title = words[1];
// string body = words[2];
// string attach = words[3];
//string date = words[4];
//string time = words[5];
//string msdId = words[6];
//string groupIDS = words[7];
//foreach (var word in words)
//Console.WriteLine(word);
Console.WriteLine("Push notification : " + message);
Debug.WriteLine("Push notification : " + message);
Debugger.Log(1, "Push", "Push notification : " + message);
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
// Show the notification since toasts aren't
// displayed when the app is currently running.
MessageBox.Show(message);
//<Temp>
// DatabaseHelperClass dbHelper = new DatabaseHelperClass();
// dbHelper.Insert(new Msg(msdId, groupIDS, type, title, body, attach, date, time, Constants.NO));
//</Temp>
});
});
}
I'm new to RabbitMQ and trying to write to a Queue and verify the message was sent. If it fails I need to know about it.
I made a fake queue to watch it fail but no matter what I see no execptions and when I am looking for a ack I always get one. I never see the BasicNack.
I'm not even sure i'm the BasicAcks is the way to go.
private void button1_Click(object sender, EventArgs e)
{
var factory = new ConnectionFactory() { HostName = "localhost" };
using (var connection = factory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
channel.QueueDeclare("task_queue", true, false, false, null);
var message = ("Helllo world");
var body = Encoding.UTF8.GetBytes(message);
channel.ConfirmSelect();
var properties = channel.CreateBasicProperties();
properties.SetPersistent(true);
properties.DeliveryMode = 2;
channel.BasicAcks += channel_BasicAcks;
channel.BasicNacks += channel_BasicNacks;
//fake queue should be task_queue
channel.BasicPublish("", "task_2queue", true, properties, body);
channel.WaitForConfirmsOrDie();
Console.WriteLine(" [x] Sent {0}", message);
}
}
}
void channel_BasicNacks(IModel model, BasicNackEventArgs args)
{
}
void channel_BasicAcks(IModel model, BasicAckEventArgs args)
{
}
For those looking for a C# answer - here is what you need.
https://rianjs.net/2013/12/publisher-confirms-with-rabbitmq-and-c-sharp
Something like this: (BasicAcks attaches an event handler - there is also BasicNacks)
using (var connection = FACTORY.CreateConnection())
{
var channel = connection.CreateModel();
channel.ExchangeDeclare(QUEUE_NAME, ExchangeType.Fanout, true);
channel.QueueDeclare(QUEUE_NAME, true, false, false, null);
channel.QueueBind(QUEUE_NAME, QUEUE_NAME, String.Empty, new Dictionary<string, object>());
channel.BasicAcks += (sender, eventArgs) =>
{
//implement ack handle
};
channel.ConfirmSelect();
for (var i = 1; i <= numberOfMessages; i++)
{
var messageProperties = channel.CreateBasicProperties();
messageProperties.SetPersistent(true);
var message = String.Format("{0}\thello world", i);
var payload = Encoding.Unicode.GetBytes(message);
Console.WriteLine("Sending message: " + message);
channel.BasicPublish(QUEUE_NAME, QUEUE_NAME, messageProperties, payload);
channel.WaitForConfirmsOrDie();
}
}
You need a Publisher Confirms
as you can read you can implement:
The transaction:
ch.txSelect(); <-- start transaction
ch.basicPublish("", QUEUE_NAME,
MessageProperties.PERSISTENT_BASIC,
"nop".getBytes());
ch.txCommit();<--commit transaction
The message is stored to the queue and to the disk.
This way can be slow, if you need performance you shouldn't use it.
You can use the Streaming Lightweight Publisher Confirms, using:
ch.setConfirmListener(new ConfirmListener() {
public void handleAck(long seqNo, boolean multiple) {
if (multiple) {
unconfirmedSet.headSet(seqNo+1).clear();
} else {
unconfirmedSet.remove(seqNo);
}
}
public void handleNack(long seqNo, boolean multiple) {
// handle the lost messages somehow
}
I hope it helps
Ok, you always get the ACK for your message sent because "Every time message is delivered to Default Exchange Successfully."
PS: You are not sending message directly to Queue, Once Exchange recevis the message it gives you ACK then it route the message to all bound queue using the routing keys if any.
I am implementing push notifications using push sharp and I have 2 types of messages I am sending RecomendationLiked and NewFollower, I can send RecomendationLiked messages as much as I want and everything works fine but sending a single NewFollower message simpley causes the service to stop responding with no exception, or any of the events called. This happens both in Production and in Development environment
Here is the service creation logic:
private void InitApplePushService()
{
try
{
string appDataPath = HttpContext.Current.Server.MapPath("~/app_data");
//***** Development Server *****//
string file = Path.Combine(appDataPath, "PushSharp.PushCert.Development.p12");
var appleCert = File.ReadAllBytes(file);
_applePushService = new ApplePushService(new ApplePushChannelSettings(false, appleCert, "XXX"));
_applePushService.OnChannelCreated += OnChannelCreated;
_applePushService.OnChannelDestroyed += OnChannelDestroyed;
_applePushService.OnChannelException += OnChannelException;
_applePushService.OnDeviceSubscriptionChanged += OnDeciveSubscriptionChanged;
_applePushService.OnDeviceSubscriptionExpired += OnDeviceSubscriptionExpired;
_applePushService.OnNotificationFailed += OnNorificationFailed;
_applePushService.OnNotificationRequeue += OnNotificationQueued;
_applePushService.OnNotificationSent += OnNOtificationSend;
_applePushService.OnServiceException += OnServiceException;
Trace.TraceInformation("ApplePushService initialized succesfully");
}
catch (Exception e)
{
Trace.TraceError("Error initializing ApplePushService : " + e);
throw;
}
}
RecomendationLiked message creation:
private void SendRecomendationLikedMessageToAppleDevice(User likingUser, Recomendation recomendation)
{
var notification = new AppleNotification();
notification.DeviceToken = recomendation.User.PushNotificationID;
notification.Payload.Alert.LocalizedKey = "NewLikeNotification";
notification.Payload.Alert.LocalizedArgs = new List<object> { likingUser.NickName };
notification.Payload.Sound = "default";
notification.Payload.AddCustom("LikingUser", likingUser.NickName);
notification.Payload.AddCustom("AlertType", "RecomendationLiked");
notification.Payload.AddCustom("ID", likingUser.ID);
notification.Payload.AddCustom("ImageUrl", likingUser.ImageUrl);
_applePushService.QueueNotification(notification);
}
NewFollower message creation:
private void SendNewFollowingUserMessageToAppleDevice(User followingUser, User followedUser)
{
var notification = new AppleNotification();
notification.DeviceToken = followedUser.PushNotificationID;
notification.Payload.Alert.LocalizedKey = "NewFollowingUserNotification";
notification.Payload.Alert.LocalizedArgs = new List<object> { followingUser.NickName };
notification.Payload.Sound = "default";
notification.Payload.AddCustom("followingUser", followingUser.NickName);
notification.Payload.AddCustom("AlertType", "NewFollowingUser");
notification.Payload.AddCustom("ID", followingUser.ID);
notification.Payload.AddCustom("ImageUrl", followingUser.ImageUrl);
Trace.TraceInformation("Trying to send notifications: "+ notification);
_applePushService.QueueNotification(notification);
//_pushService.QueueNotification(notification);
}
The first one works, the second kills the push service silently...
Any ideas?
Solved it finally...
The issue is with the length of the json string that is generated. it seems that the maximum is 255 chars. anything higher and it fails silently...
beware.
Amit