Click here to Skip to main content
12,623,930 members (29,908 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


28 bookmarked

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


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

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 usingpushsharp 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")
    //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!
        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 
        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

    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")
    //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
     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(
     .WithJson("{\"alert\":\"Hello World!\",

Step 8: Stop and Wait for the Queues to Drain

push.StopAllServices(waitForQueuesToFinish: true); 

That's it, we are good to go.  


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


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: or

You may also be interested in...


Comments and Discussions

GeneralSample Project Pin
Kaushik Dhameliya29-Aug-16 19:14
memberKaushik Dhameliya29-Aug-16 19:14 
QuestionThe type or namespace name 'IPushChannel' could not be found Pin
Member 1252818117-May-16 0:07
memberMember 1252818117-May-16 0:07 
AnswerRe: The type or namespace name 'IPushChannel' could not be found Pin
anilmathpati21-Jul-16 2:25
memberanilmathpati21-Jul-16 2:25 
QuestionMessage Removed Pin
yedhuvamshi10-May-16 22:35
memberyedhuvamshi10-May-16 22:35 
QuestionTo ad Custom data with gcm notification Pin
NaniCh15-Feb-16 21:08
memberNaniCh15-Feb-16 21:08 
QuestionHow can we send the json object, in pushsharp notification Pin
vasanthrJ8-Dec-15 18:12
membervasanthrJ8-Dec-15 18:12 
QuestionAndroid notification: InvalidRegistration Pin
Wismeryl30-Oct-15 6:03
memberWismeryl30-Oct-15 6:03 
QuestionAuthentication failed because remote party has closed the transport stream Pin
Member 109585721-Sep-15 21:33
memberMember 109585721-Sep-15 21:33 
AnswerRe: Authentication failed because remote party has closed the transport stream Pin
venudreamsb4u18-Sep-15 0:18
membervenudreamsb4u18-Sep-15 0:18 
BugSending Push Message On Apple through Sandbox Pin
ankitsoftdev18-Aug-15 8:59
memberankitsoftdev18-Aug-15 8:59 
QuestionIOS Push Notification Pin
Mansi Arora13-May-15 21:13
memberMansi Arora13-May-15 21:13 
QuestionNot Coming notifications for both iphone and Android Pin
NaniCh29-Apr-15 6:03
memberNaniCh29-Apr-15 6:03 
QuestionBatch push Pin
sasi rekha13-Oct-14 22:37
membersasi rekha13-Oct-14 22:37 
AnswerRe: Batch push Pin
ersumitsahu27-Mar-15 0:06
memberersumitsahu27-Mar-15 0:06 
QuestionUsing Pushsharp sending notification on local but on production its not receiving on Device Pin
Vipin Mampully6-Oct-14 22:14
memberVipin Mampully6-Oct-14 22:14 
QuestionGot an error Pin
Member 1091563629-Sep-14 22:30
memberMember 1091563629-Sep-14 22:30 
SuggestionNot able to send pushnotification in Apple device. Pin
pdsweetpd22820-Sep-14 7:12
memberpdsweetpd22820-Sep-14 7:12 
QuestionI don´t know where can I get a list of devices Pin
Member 1104865931-Aug-14 7:11
memberMember 1104865931-Aug-14 7:11 
QuestionSwitching between devices/applications Pin
Lakshminivas6-Aug-14 14:33
memberLakshminivas6-Aug-14 14:33 
QuestionIphone notification is working when my application host on server Pin
dotnetdelhi20-May-14 2:56
memberdotnetdelhi20-May-14 2:56 
QuestionCertificate file Pin
Z@clarco31-Mar-14 2:52
memberZ@clarco31-Mar-14 2:52 
AnswerRe: Certificate file Pin
Mangesh V. Devikar13-May-14 4:08
professionalMangesh V. Devikar13-May-14 4:08 
QuestionPush notification not working in wcf service on server Pin
sushilchauhan21-Mar-14 5:09
membersushilchauhan21-Mar-14 5:09 
AnswerRe: Push notification not working in wcf service on server Pin
Mangesh V. Devikar13-May-14 4:09
professionalMangesh V. Devikar13-May-14 4:09 
QuestionHow to get response Pin
sasi rekha18-Feb-14 21:12
membersasi rekha18-Feb-14 21:12 

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.

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