Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Using PushSharp to Send Notifications to iOS and Android

0.00/5 (No votes)
12 Oct 2013 4  
Implementing pushsharp library for sending notifications from ASP.NET application

Introduction

This tip simply puts forth the straight forward answer for how to send push notifications to iOS and Android devices using PushSharp. To download the DLL and for raw information, visit https://github.com/Redth/PushSharp.

Using the Code

Let me set the stage first. You have a page where the admin will write some message, on submit you require to push this message to all your ios and Android subscribers. For this purpose, I am using pushsharp that I have successfully used many times. I take no credit in developing this library, but I am merely trying to assemble things for ready to use.

Let's start.

Step 1: Add namespaces

using PushSharp;
using PushSharp.Android;
using PushSharp.Apple;
using PushSharp.Core;

Step 2: Getting the Events Ready

//Currently it will raise only for android devices
        static void DeviceSubscriptionChanged(object sender, 
        string oldSubscriptionId, string newSubscriptionId, INotification notification)
        {
            //Do something here
        }

        //this even raised when a notification is successfully sent
        static void NotificationSent(object sender, INotification notification)
        {
            //Do something here
        }

        //this is raised when a notification is failed due to some reason
        static void NotificationFailed(object sender, 
        INotification notification, Exception notificationFailureException)
        {
            //Do something here
        }

        //this is fired when there is exception is raised by the channel
        static void ChannelException
        	(object sender, IPushChannel channel, Exception exception)
        {
            //Do something here
        }

        //this is fired when there is exception is raised by the service
        static void ServiceException(object sender, Exception exception)
        {
            //Do something here
        }

        //this is raised when the particular device subscription is expired
        static void DeviceSubscriptionExpired(object sender, 
        string expiredDeviceSubscriptionId, 
        	DateTime timestamp, INotification notification)
        {
            //Do something here
        }

        //this is raised when the channel is destroyed
        static void ChannelDestroyed(object sender)
        {
            //Do something here
        }

        //this is raised when the channel is created
        static void ChannelCreated(object sender, IPushChannel pushChannel)
        {
            //Do something here
        }

Step 3: The Method

Following is my method to send the notification. txtNotification is my textbox wherein user types the message to be sent:

protected void btnSubmit_Click(object sender, EventArgs e)
{
    if (!string.IsNullOrEmpty(txtNotification.Text))
    { 
     .... code continued in further steps
    } 
} 

Step 4: Wire Up All the Events

//create the puchbroker object
var push = new PushBroker();
//Wire up the events for all the services that the broker registers
push.OnNotificationSent += NotificationSent;
push.OnChannelException += ChannelException;
push.OnServiceException += ServiceException;
push.OnNotificationFailed += NotificationFailed;
push.OnDeviceSubscriptionExpired += DeviceSubscriptionExpired;
push.OnDeviceSubscriptionChanged += DeviceSubscriptionChanged;
push.OnChannelCreated += ChannelCreated;
push.OnChannelDestroyed += ChannelDestroyed;

Step 5: Get All Device ids to Which Message has to be Sent

//Here I am looping on my device collection. 
//Use your own way to handle this
List<Device> rows = 
	new List<Device>(CommonMethods.entity.Devices.ToList());
foreach (Device row in rows)
{   

Step 6: Handling ios Notification

Ask your ios developer for the key and password. Attach the key file in your solution and the rest is below. Don't worry, it's only three lines, rest is all commenting:

if (row.devicename == "ios")
{
    //-------------------------
    // APPLE NOTIFICATIONS
    //-------------------------
    //Configure and start Apple APNS
    // IMPORTANT: Make sure you use the right Push certificate.  Apple allows you to
    //generate one for connecting to Sandbox, and one for connecting to Production.  You must
    // use the right one, to match the provisioning profile you build your
    //   app with!
    try
    {
        var appleCert = File.ReadAllBytes(Server.MapPath("Resources/key.p12"));
        //IMPORTANT: If you are using a Development provisioning Profile, you must use
        // the Sandbox push notification server 
        //  (so you would leave the first arg in the ctor of ApplePushChannelSettings as
        // 'false')
        //  If you are using an AdHoc or AppStore provisioning profile, you must use the 
        //Production push notification server
        //  (so you would change the first arg in the ctor of ApplePushChannelSettings to 
        //'true')
        push.RegisterAppleService(new ApplePushChannelSettings(true, appleCert, "password")); 
        //Extension method
        //Fluent construction of an iOS notification
        //IMPORTANT: For iOS you MUST MUST MUST use your own DeviceToken here that gets
        // generated within your iOS app itself when the Application Delegate
        //  for registered for remote notifications is called, 
        // and the device token is passed back to you
        push.QueueNotification(new AppleNotification()
                                    .ForDeviceToken(row.deviceid)//the recipient device id
                                    .WithAlert(txtNotification.Text)//the message
                                    .WithBadge(1)
                                    .WithSound("sound.caf")
                                    );


    }
    catch (Exception ex)
    {
        throw ex;
    }
}

Step 7: Handling the Android

Ask your Android developer for the key and password. Attach the key file in your solution and the rest is below. Don't worry, it's only two lines, rest is all commenting:

if(row.devicename == "android")
{
    //---------------------------
    // ANDROID GCM NOTIFICATIONS
    //---------------------------
    //Configure and start Android GCM
    //IMPORTANT: The API KEY comes from your Google APIs Console App, 
    //under the API Access section, 
    //  by choosing 'Create new Server key...'
    //  You must ensure the 'Google Cloud Messaging for Android' service is 
    //enabled in your APIs Console
    push.RegisterGcmService(new 
     GcmPushChannelSettings("YOUR Google API's Console API Access  API KEY for Server Apps HERE"));
    //Fluent construction of an Android GCM Notification
    //IMPORTANT: For Android you MUST use your own RegistrationId 
    //here that gets generated within your Android app itself!
    push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(
    "DEVICE REGISTRATION ID HERE")
     .WithJson("{\"alert\":\"Hello World!\",
     \"badge\":7,\"sound\":\"sound.caf\"}"));
}

Step 8: Stop and Wait for the Queues to Drain

push.StopAllServices(waitForQueuesToFinish: true); 

That's it, we are good to go. Smile | :)  

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here