Click here to Skip to main content
15,885,278 members
Articles / Web Development / ASP.NET
Tip/Trick

Using PushSharp to Send Notifications to iOS and Android

Rate me:
Please Sign up or sign in to vote.
4.64/5 (19 votes)
12 Oct 2013CPOL1 min read 210.2K   28   36
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

C#
using PushSharp;
using PushSharp.Android;
using PushSharp.Apple;
using PushSharp.Core;

Step 2: Getting the Events Ready

C#
//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:

C#
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

C#
//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

C#
//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:

C#
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:

C#
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

C#
push.StopAllServices(waitForQueuesToFinish: true); 

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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Founder Enziq Solutions Pvt. Ltd.
India India
My key portfolios at Enziq Solutions includes Business Development and Strategy and overseeing Technology operations.
Read more about me at: http://enziq.com/site/Company/mangesh.html or http://mangeshdevikar.enziq.com/about-me/

Comments and Discussions

 
QuestionError:The maximum number of Send attempts to send the notification was reached! Pin
gj094-Feb-14 0:05
gj094-Feb-14 0:05 
AnswerRe: Error:The maximum number of Send attempts to send the notification was reached! Pin
Mangesh V. Devikar16-Feb-14 22:57
professionalMangesh V. Devikar16-Feb-14 22:57 
QuestionDo you have sample code Pin
rperetz28-Jan-14 8:00
rperetz28-Jan-14 8:00 
AnswerRe: Do you have sample code Pin
Mangesh V. Devikar16-Feb-14 22:49
professionalMangesh V. Devikar16-Feb-14 22:49 
Questionscheduling notifications Pin
Neha Rustagi26-Dec-13 22:36
professionalNeha Rustagi26-Dec-13 22:36 
AnswerRe: scheduling notifications Pin
Mangesh V. Devikar16-Feb-14 22:43
professionalMangesh V. Devikar16-Feb-14 22:43 
GeneralMy vote of 5 Pin
cassio.scherer25-Oct-13 7:51
professionalcassio.scherer25-Oct-13 7:51 
GeneralRe: My vote of 5 Pin
Mangesh V. Devikar26-Oct-13 3:07
professionalMangesh V. Devikar26-Oct-13 3:07 
thanks Smile | :)

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.