Click here to Skip to main content
Click here to Skip to main content

Using PushSharp to Send Notifications to iOS and Android

, 12 Oct 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Mangesh V. Devikar
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/
Follow on   LinkedIn

Comments and Discussions

 
QuestionBatch push Pinmembersasi rekha13-Oct-14 22:37 
AnswerRe: Batch push Pinmemberersumitsahu27-Mar-15 0:06 
QuestionUsing Pushsharp sending notification on local but on production its not receiving on Device PinmemberVipin Mampully6-Oct-14 22:14 
QuestionGot an error PinmemberMember 1091563629-Sep-14 22:30 
SuggestionNot able to send pushnotification in Apple device. Pinmemberpdsweetpd22820-Sep-14 7:12 
QuestionI don´t know where can I get a list of devices PinmemberMember 1104865931-Aug-14 7:11 
QuestionSwitching between devices/applications PinmemberLakshminivas6-Aug-14 14:33 
QuestionIphone notification is working when my asp.net application host on server Pinmemberdotnetdelhi20-May-14 2:56 
QuestionCertificate file PinmemberZ@clarco31-Mar-14 2:52 
AnswerRe: Certificate file PinprofessionalMangesh V. Devikar13-May-14 4:08 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150327.1 | Last Updated 12 Oct 2013
Article Copyright 2013 by Mangesh V. Devikar
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid