Click here to Skip to main content
15,885,365 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

 
QuestionIs pushSharpb still relative Pin
lkoutsavlis13-Mar-18 1:54
lkoutsavlis13-Mar-18 1:54 
AnswerRe: Is pushSharpb still relative Pin
Member 1375119428-Mar-18 1:43
Member 1375119428-Mar-18 1:43 
GeneralSample Project Pin
Kaushik Dhameliya29-Aug-16 18:14
Kaushik Dhameliya29-Aug-16 18:14 
QuestionThe type or namespace name 'IPushChannel' could not be found Pin
Member 1252818116-May-16 23:07
Member 1252818116-May-16 23:07 
AnswerRe: The type or namespace name 'IPushChannel' could not be found Pin
anilmathpati21-Jul-16 1:25
anilmathpati21-Jul-16 1:25 
QuestionTo ad Custom data with gcm notification Pin
NaniCh15-Feb-16 20:08
NaniCh15-Feb-16 20:08 
QuestionHow can we send the json object, in pushsharp notification Pin
vasanthrJ8-Dec-15 17:12
vasanthrJ8-Dec-15 17:12 
QuestionAndroid notification: InvalidRegistration Pin
Wismeryl30-Oct-15 5:03
Wismeryl30-Oct-15 5:03 
QuestionAuthentication failed because remote party has closed the transport stream Pin
Member 109585721-Sep-15 20:33
Member 109585721-Sep-15 20:33 
AnswerRe: Authentication failed because remote party has closed the transport stream Pin
venudreamsb4u17-Sep-15 23:18
venudreamsb4u17-Sep-15 23:18 
BugSending Push Message On Apple through Sandbox Pin
ankitsoftdev18-Aug-15 7:59
ankitsoftdev18-Aug-15 7:59 
QuestionIOS Push Notification Pin
Mansi Arora13-May-15 20:13
Mansi Arora13-May-15 20:13 
QuestionNot Coming notifications for both iphone and Android Pin
NaniCh29-Apr-15 5:03
NaniCh29-Apr-15 5:03 
QuestionBatch push Pin
sasi rekha13-Oct-14 21:37
sasi rekha13-Oct-14 21:37 
AnswerRe: Batch push Pin
ersumitsahu26-Mar-15 23:06
ersumitsahu26-Mar-15 23:06 
QuestionUsing Pushsharp sending notification on local but on production its not receiving on Device Pin
Vipin Mampully6-Oct-14 21:14
Vipin Mampully6-Oct-14 21:14 
QuestionGot an error Pin
Member 1091563629-Sep-14 21:30
Member 1091563629-Sep-14 21:30 
SuggestionNot able to send pushnotification in Apple device. Pin
pdsweetpd22820-Sep-14 6:12
pdsweetpd22820-Sep-14 6:12 
QuestionI don´t know where can I get a list of devices Pin
Member 1104865931-Aug-14 6:11
Member 1104865931-Aug-14 6:11 
AnswerRe: I don´t know where can I get a list of devices Pin
Member 111376636-Jul-17 7:41
Member 111376636-Jul-17 7:41 
QuestionSwitching between devices/applications Pin
Lakshminivas6-Aug-14 13:33
Lakshminivas6-Aug-14 13:33 
QuestionIphone notification is working when my asp.net application host on server Pin
dotnetdelhi20-May-14 1:56
dotnetdelhi20-May-14 1:56 
QuestionCertificate file Pin
Z@clarco31-Mar-14 1:52
Z@clarco31-Mar-14 1:52 
AnswerRe: Certificate file Pin
Mangesh V. Devikar13-May-14 3:08
professionalMangesh V. Devikar13-May-14 3:08 
QuestionPush notification not working in wcf service on server Pin
sushilchauhan21-Mar-14 4:09
sushilchauhan21-Mar-14 4:09 

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.