PushSharp 3.0 – The Push Awakens!

PushSharp 3.0Some of you may be familiar with a little library called PushSharp.  If you’re not, it’s a C# library that helps developers send push notifications to various platforms.  I started this effort a few years ago, and somehow during those years, seemingly despite my best effort, this thing became fairly popular.

Now, more recently (ok-ok, for the last year at least), PushSharp has been sorely neglected.  It still works for the most part, especially if you fork it and merge in some of the open pull requests to improve it like the many others that have already done so, but it’s old, it’s out-dated, and it needs some love.

While I can make a number of excuses for the project’s inactivity (like a new addition to my family, a new job, and a new house), It’s clear that developers still want a C# library to send push notifications, and my suggestion to use Amazon EC2 and Azure (both great economical alternatives) just doesn’t cut it.

evolve-2014At the last Xamarin Evolve conference (I now work at Xamarin, by the way) I was humbled by the number of people who flagged me down and asked me about PushSharp.  In fact, I felt ashamed for pretty much abandoning the project at that point, and vowed to myself to make things better.  I decided on the flight home to start rewriting the library, this time with the wonderful async/await, Tasks, and HttpClient at its core.

If you’re keeping score, Evolve was awhile a long time ago now.  I lost focus again since I started that rewrite, with one of the big reasons being that I had become extremely frustrated with Apple’s APNS protocol (again), or more-so its lack of defined behaviour, unorthodox design, and lack of resources available to test this thing at scale.  This is and always has been the achilles heel of PushSharp.

Enter WWDC15.  Although I didn’t notice it until very recently, Apple announced they are going to add a HTTP/2 based protocol for sending APNS notifications, this time with a success/fail response for each message, and based around a documented standard.  Hearing this news made me extremely excited, and motivated to get back to work on PushSharp.

At last.

Enter PushSharp 3.0.  I’ve invested more time and energy into PushSharp v3.0, and this time, by virtue of public announcement, am dedicating myself to completing it!

The API has been compeltely overhauled to make extensive use of Tasks, async/await, and HttpClient as I mentioned before.  The library already scales better, and is more reliable, and I do believe this should be a worthy successor to the neglected bits currently rotting away.

With this release, the focus is on simplicity and reliability.  This also means API has changed quite a bit.  For instance you’ll be responsible for constructing your own message payloads on iOS and Windows now (the old fluent helper methods became obsoleted too quickly and introduced too many bugs).  Don’t let that fool you though, it’s still pretty simple to use:

// Configuration
var config = new ApnsConfiguration ("push-cert.pfx", "push-cert-pwd");

// Create a new broker
var broker = new ApnsServiceBroker (config);

// Wire up events
broker.OnNotificationFailed += (notification, exception) => {
    Console.WriteLine ("Notification Failed!");
};
broker.OnNotificationSucceeded += (notification) => {
    Console.WriteLine ("Notification Sent!");
};

// Start the broker
broker.Start ();

// Queue a notification to send
broker.QueueNotification (new ApnsNotification {
        DeviceToken = "device-token-from-device",
        Payload = JObject.Parse ("{\"aps\":{\"badge\":7}}")
    });

// Stop the broker, wait for it to finish   
broker.Stop ();

So, give the README a look, and jump on the Gitter.im channel if you have questions or are interested in helping me test at scale.

Currently all of the 3.0 code is available in the 3.0-dev branch.  You can find -PreRelease NuGet packages on NuGet.org too.  The API is quite a bit different than before.

Thanks to everyone who has used PushSharp, who has said nice things about it (deserved or otherwise), and hopefully this library still has a bright future ahead!

  • Vinicius Henrique

    Thanks Redth. I was awaiting a long time for this update =). You mentioned that the fluent extension methods helper became obsolete. Do you have plans to build a true fluent interface for PushSharp 3.0?

  • Damien Sawyer

    Thanks for your ongoing work with this!

  • Gustavo Castro

    Thanks Redth to your awesome work on this. I would to know if I can use the PushSharp.Google (GCM) to send IOS push notifications with PushSharp or I should use PushSharp.Apple to do this? Thanks in advance.

  • Saurabh Mehta

    @redth

    PushSharp 3.0, is it gonna be compatible with Xamarin Forms v3 and above, the nuget installation of the Beta version throws error

    Regards,
    Saurabh

    • PushSharp is a server side library, meant for sending notifications from your server to various push notification providers. It’s not a client library meant to be used in Xamarin apps.

  • siva krishna

    hey, Im getting folllwing error for my new Apps.

    You have selected the Production server, yet your Certificate does not appear to be the Production certificate! Please check to ensure you have the correct certificate!” (Server team is using Pushsharp to send notification

    Where as all of my old apps getting notifications. let me know the possible reasons ..

  • Akshar Patel

    Will this be compatible with the new dotnetcore?

    • Not sure if it is currently (probably not) but that’s one of my goals, yes 🙂

  • Aaron Newsom

    Thanks for working on this, I certainly appreciate it

  • Laszlo

    Why don’t you guys just use PushWizard? Already set up, easy to use, you don’t need your own server and of course it is free.

    • That may be a great option for some, just like Azure or EC2 is a great option for some (and I’ve been pretty vocal about using them as an alternative to PushSharp in the past), however not everyone has the same requirements and some business requirements may be to not send out notification data to third party services.

      Also, it looks like your suggestion may only work with iOS. PushSharp supports several platforms’ push notification implementations.

      In any case, thanks for the suggestion!

  • MarkJoel

    There is something I have been looking for but haven’t found anything. Maybe this will help me? IDK:
    I need to register a Windows client to receive push messaging. I can send down to an android app though a thousand different ways, but if I want to send a message from the Android device (or iPhone, etc) back to the laptop, its no dice.
    Is there anything in PushSharp 3.0 that might help me?

  • Javier Collado Valle

    Will it be possible to send push notifications from behind a proxy?

    • Eventually, hopefully, but not right now, sorry.

      • Guy Montag

        Hi, i wrote some Code to send notifications to APNS through a Proxy with PushSharp. Check your pull requests on GitHub and let me know if you like it.
        Cheers!

  • Lucas Stern

    How can i set proxy in apple PushSharp ? I need set proxy in send nottification and in feedback. Thanks.

  • Jamal Zeynalov

    Hi, Jonathan. First of all thank you for the great job! We are actively using yor lib. Can you please tell when do you plan to release a stable version 3.0? Thank you in advance.

    Best regards, Jamal.

  • tito miky

    Hello, in this link https://github.com/Redth/PushSharp/tree/3.0-dev-apnshttp2 you say you need help to test very large scale APNS. We send thousands of APNS with version 2 and we would like to update to 3. How can I help? THank you!

  • JohnnyXP64

    Where can I donate so that you get more motivation furnishing this?

    • While I appreciate the idea, no donations please 🙂 PR’s are always welcome though!

  • Paul Smith

    I’m getting a weird error. probably my fault, but maybe you can shed some light. When I debug and send a push to GCM, it works first time, but when I try to send another to the same Android token I get this error:

    One or more errors occurred.System.UnauthorizedAccessException: GCM Authorization Failed

    at PushSharp.Google.GcmServiceConnection.processResponseError(HttpResponseMessage httpResponse, GcmNotification notification)

    at PushSharp.Google.GcmServiceConnection.d__6.MoveNext()

    I’ve gone through the debugs and cannot see any difference between the first send process that sends OK and the next that fails.

    Any ideas?

    • Paul Smith

      Any update on this???

  • Arsénio Costa

    Im getting the same issue as @disqus_6RKT1y9izC:disqus .

    • Paul Smith

      Did u find a fix for this? I’ve had no reply

      • tito miky

        Hello Paul, do you still have the problem? Do you recommend to migrate from version 2 to 3?

        Thank you

    • Blog comments aren’t a great medium for posting bug reports or asking questions. Please use the GitHub issue tracker for this!

  • yelangHzx

    hi,thank you for your PushSharp.
    I have a quetion about Apns,how can I get the devicetoken from the push result?
    Whether its success or wrong,I want log the correspongind devicetoken.

    broker.OnNotificationSucceeded += (notification) => {

    Console.WriteLine (“Notification Sent!”);

    };

    • yelangHzx

      Sorry,I see.INotification is a baseClass.i find the devicetoken.

  • Rocco King

    Could you please provide complete example for sending GCM and Apple push notification using the new PushSharp 3.x library ? None of the codes that I used for PushSharp 2.x works and I cannot find any complete examples anywhere. Thanks

    • The README has a bit of an example, or you can look at the unit tests for some samples too.

  • Yongjie Li

    hi. thank you for PushSharp. However, when i download from github,i could not compile the source code. Because there has some C# 6.0 syntax. Where can i find the source code that can be compiled in lower .net framework.(PS: i use visual studio 2013 and .net framework 4.5). Thanks a lot.

    • DeathRay

      If the code uses C# 6.0 language features then you’ll need to install the C# 6.0 compiler.

  • calvin

    when i use the Apple Development certification, it return the error: Your Certificate is not in the new combined Sandbox/Production APNS certificate format, please create a new single certificate to use.

  • SStratis

    GCM now allows the ability to send push notifications to both platforms. Does PushSharp support this, since it supports sending messages directly to GCM?

  • WicMan

    Hi Redth, I am currently using PushSharp to send push notifications to my Xamarin application. I have followed a few tutorials on getting a server setup and I have managed to get the GCM version sending push notifications and followed your, and other instructions on configuring iOS but I permanently get an error stating “The maximum number of Send attempts to send the notification was reached!”. Do you have any ideas of where I could possibly be going wrong?

  • Vagelis Dermos

    Hi to all. I want to send push to winmobile with Image. I “ToastImageAndText04”, but I do not know hot to add the image. The image will be from my local HD. The app is a WinForm app.
    Thanks in advance

  • Dwarola

    I am using push sharp to send push to ios with latest p12 certificates, it is working fine from local environment. but it is not working on webserver.
    please suggest.

    • neal

      Are you getting System.Net.Sockets.SocketException?

  • gopikrishna srinivasula

    Hi,
    Recently we have updated PushSharp verson from 2.2.1 to 4.0.1 and used the new code. The code is working with http servers, but not with https.
    My code is as follows

    #region Apple Notfications Setup
    ApnsConfiguration apnsConfig = null;
    if (ConfigurationManager.AppSettings[“IsProduction”].ToString().Trim().ToLower() == “false”)
    {
    var appleCert = File.ReadAllBytes(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, “AppleDeveloperCertificate.p12”));
    apnsConfig = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Sandbox, appleCert, “password”);
    }
    else
    {
    var appleCert = File.ReadAllBytes(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, “AppleProductionCertificate.p12”));
    apnsConfig = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Production, appleCert, “password”);
    }

    var apnsBroker = new ApnsServiceBroker(apnsConfig);
    apnsBroker.OnNotificationFailed += (notification, aggregateEx) =>
    {
    aggregateEx.Handle(ex =>
    {
    // See what kind of exception it was to further diagnose
    if (ex is ApnsNotificationException)
    {
    var notificationException = (ApnsNotificationException)ex;

    // Deal with the failed notification
    var apnsNotification = notificationException.Notification;
    var statusCode = notificationException.ErrorStatusCode;

    Utility.WriteLog(“IOS Push Notifications: Apple Notification Failed: ID=” + apnsNotification.Identifier + “, Code=” + statusCode);

    }
    else {
    // Inner exception might hold more useful information like an ApnsConnectionException
    Utility.WriteLog(“IOS Push Notifications: Apple Notification Failed for some unknown reason : ” + ex.InnerException);
    }

    // Mark it as handled
    return true;
    });
    };

    apnsBroker.OnNotificationSucceeded += (notification) =>
    {
    Utility.WriteLog(“IOS Push Notifications: Apple Notification Sent!”);
    };

    // Start the broker
    apnsBroker.Start();
    #endregion

    var jobject = JObject.FromObject(new
    {
    aps = new
    {
    alert = “Message from Product”,
    badge = 10,
    sound = “iPhone_Tritone.mp3”,
    }
    });

    apnsBroker.QueueNotification(new ApnsNotification
    {
    DeviceToken =devicetoken,
    Payload = jobject
    });

    Is there any changes required for https servers? Please help.

  • Ulises Dascalakis

    DATA JSON not found 🙁

  • Zubair Sayed

    hi ,
    i m using FCM for send push notification to Android they get Struct in Back end and After sometimes they came all at once and is that thing handled in pushsharp