Sending Apple Push Notifications in ASP.NET and C# – part 4 (Moon-APNS C# wrapper class)

Sorry for the delay, please email me on if you had any questions about this article series and Ill help you as much as i can.

Bellow is a wrapper class for Moon-APNS Library, using this wrapper class is really easy.

First you need to reference Moon-APNS project in your solution, also you can build them and reference dll files.

I have added a detailed post about Moon-APNS and how you can use it here :

I have added lots of comments in the source code,so its really easy to find your way around the code. but feel free to email me if you had any questions.


47 thoughts on “Sending Apple Push Notifications in ASP.NET and C# – part 4 (Moon-APNS C# wrapper class)

  1. Prashant says:


    I am facing some problem in sending the notifications through C# code.
    I have created a test application on MAC which is deployed on iPhone to receive push notifications.
    The iPhone receives push notifications successfully from a sample PHP code which is build to MAC. But when I try to send the same from Windows machine through C# code it fails to deliver the push message.
    The certificate has been created in following ways.
    1) Created a CSR file from KeyChainAccess on MAC.
    2) This has created a private key in the KeyChainAccess.
    3) Selected this private key, right clicked and export.
    4) Saved the private key as “PushKey.p12” with blank passphrase.
    5) I followed all the steps later like creating AppId, Provisioning Profile which gave me certificate which is saved as aps_developer_identity.cer.
    6) The PushKey.P12 and aps_developer_identity.cer are then converted into .PEM file which again combined to from one .pem file which is used by PHP code to send push notifications successfully. But the C# code uses .P12 file. I have tried to use same p12 file generated on MAC in the C# project but the code fails to deliver the PushNotifcation to the Apple server.
    The response I get from the Apple server is “Connecting…” and “Failed”

    Please could you advise if I am using correct .P12 file or is there any other way to generate .P12 file for windows.
    Awaiting your reply as I am stuck up and not able to move forward.

    Thank you very much.



    • Hi Prashant,
      I’m a .net developer, and up to now i have received the certificates from our IPhone developers team.
      I’ll ask the about the certificate export and will email you the details.

    • Joseph Gagliardo says:

      This took me forever to figure out but I finally pieced it all together from the minor clues people left. You need to download the certificate for the APPID that you register on the developer portal. That certificate must be converted into a P12 format to be used on Windows. These commands in UNIX finally did it for me:

      Step 1:

      openssl x509 -in aps_developer_identity.cer -inform DER -out aps_developer_identity.pem -outform PEM}

      Where aps_developer_identity.cer is the file you download from the portal

      Step 2:

      openssl pkcs12 -nocerts -out APSCertificates.pem -in APSCertificates.p12

      Where APSCertificates.p12 is a file you export from the Mac Keychain. This is critical, you must import the certificate from the portal into keychain. Find it in My Certificates, open the disclosure triangle and highlight both the certificate and the private key, then right click and export them. Give them a password and save them to a p12 file.

      Step 3:

      openssl pkcs12 -export -in aps_developer_identity.pem -out aps_developer_identity.p12 -inkey APSCertificates.pem

      You will be prompted a few times for the password you used to export the certificate and private key in Keychain and prompted again for new passwords to re-encrypt it all, but in the end you will have the file aps_developer_identity.p12 which you need to move to windows, then import it into both the Personal and Trusted Root sections of certificate manager in MMC. Then in C# when you use MoonAPNS and call the PushNotification class you give it a path to that certificate. Also make sure to remove spaces from the device token.

      I don’t know why someone couldn’t have made it this simple in all one place to start with instead of making me and no doubt many others spend hours piecing this all together. But hopefully this will spare anyone in the future the pain I suffered in finding this all.

  2. Derek Brennna says:

    Hi, I don’t know if you can help me out here – I’ve read your articles on APNS and have an app configured to go. I am having major issues however with getting the Dot Net code to work. The problem seems to be around the certificates. I must be doing something stupid here, but cannot figure out what, and I’ve spent 2 days on it so far (wouldn’t bug you with this otherwise).

    Specifically, the code that tries to open the certificates fails – i.e….

    //Need to load the private key seperately from apple
    if (string.IsNullOrEmpty(p12FilePassword))
    certificate = new X509Certificate2(System.IO.File.ReadAllBytes(p12File));
    certificate = new X509Certificate2(System.IO.File.ReadAllBytes(p12File), p12FilePassword);

    I have tried various things around certificates as follows.

    1/ I found that simply exporting the private key as a p12 and trying to import that into the local computer Personal Certificates fails. It give an error saying that the file is empty. To get round this, I export the certificate and private together as a .p12 and import that. This works in as much as the certificate installs. I then import the aps_developer_identity.cer (not the developer_identity.cer) separately. This also installs. I repeat these steps for the Trusted Root Cert Authority. These also import.

    In code however, trying to open the .p12 fails with a cryptographic error. The event log shows the info at the bottom of this mail.

    Am I using the correct cert – Should I be exporting just the private Key as a p12 (and doing something additional to get it to install without error?).

    If you can shed any light on this I would be really grateful as I’m pretty much at a dead end.

    I’ll post this as a comment under your tutorial also.

    Derek Brennan.

    • Hi Derek,
      I’m a .net developer, and up to now i have received the certificates from our IPhone developers team.
      I’ll ask the about the certificate export and will email you the details.

    • Blaine says:

      I am having the exact same problem using the MoonAPNS library. Were you ever able to find a solution?

      I have tested the firewall settings, tested the certificate and verified notifications can be sent from a Windows 7 and Windows Server 2003 machine. Problem is with a Windows Server 2008 machine.

  3. Vipin Rathore says:


    I tried it on localhost and its working here, As I tried it on server i got error;

    System.Security.Cryptography.CryptographicException: An internal error occurred.

    Statement where this problem generating.

    NotificationService service = new NotificationService(sandbox, p12Filename, p12FilePassword, 1);

    Could you please help to resolve this problem?

    • Ilkka says:

      Hi, Vipin & others, did anyone of you solve this error? Localhost also working here but after deployed to server I get the same error:

      System.Security.Cryptography.CryptographicException: An internal error occurred.

    • Ronen says:

      i had the same problem myself, don’t remember how i fixed it but i found the solution non the web looking for details about this error.

  4. Shailendrasinh Parmar says:

    Hi I need to provide facitlity to send messages to iPhone through push notifications. And for that I need to setup it on my client’s server.

    So, How can I do it? Can you please provide me steps. You said that I need to reference the Moon-apns project in application. Will the application be a website?

    How to do this please?

  5. Please explain the code

    1/ var payload1 = new NotificationPayload(“Device Token”, “test message”, 1, “default”);
    What is the value of DEVICE TOKEN? Apple requires the following items for each payload:

    – An alert message to display to the user
    – A number to badge the application icon with
    – A sound to play

    DEVICE TOKEN is not mentioned

    2/ var push = new PushNotification(true, “DevPushCertificate.p12 location”, “password”);
    What location means? A path to the .p12 file in your PC?

    Please clarify if the example code below is correct:
    var push = new PushNotification(true, “C:/Users/roamer/Desktop/DevPushCertificate.p12″, ” “);


  6. Cafe Coder says:

    Problem with: “System.Security.Cryptography.CryptographicException: An internal error occurred.” Fixed.

    Credit for leading me to the cause.

    In PushNotification.cs > public PushNotification(bool useSandbox, string p12File, string p12FilePassword) > change this line from:

    _certificate = string.IsNullOrEmpty(p12FilePassword)? new X509Certificate2(File.ReadAllBytes(p12File)): new X509Certificate2(File.ReadAllBytes(p12File), p12FilePassword);


    _certificate = string.IsNullOrEmpty(p12FilePassword)? new X509Certificate2(File.ReadAllBytes(p12File)): new X509Certificate2(File.ReadAllBytes(p12File), p12FilePassword, X509KeyStorageFlags.MachineKeySet);

    Notice “, X509KeyStorageFlags.MachineKeySet” was added.

    After that change this fine lib works in both the console app in and in my aspx/c# page.

  7. jignesh says:

    Can some one provide me steps on how to get started with this class files. I have downloaded the project but what next? I dont know what to do next.

  8. Hi.

    First of all, thank you for the great tutorial.
    Unfortunately, it does not work right on my PC.

    I can send the push message, but nothing happens.
    No error, no return code.

    Just nothing.

    Any idea?

  9. Aswin says:

    Hi, I tried to run the application on localhost and when this code is executed, I always get this exception : “The operation is not allowed on non-connected sockets.”
    It seems I can’t connect to APNS Server. Any idea how to solve it?

  10. Vijay says:

    I have registered .p12 and .cer files in my management console as described in article.

    But I am getting below error.
    “An unknown error occurred while processing the certificate”.

    Can you please help me to resolve this.

    Thanks in advance.

  11. jesseliu says:

    I get this error,the error is “Does not recognize the certificate provided to the security package”, I don’t konw what the problem is!

  12. Nagender says:

    hi all,

    i have used moonApns dll in pushnotification webservice, its working in development server where as in production server getting the wrror like “Internal Error Occured”…

    Plesae get me out from this issue….

    thanks & Regards

    • Xavi says:

      I have the same issue. While in development everything goes ok, once the app is in production I can’t send push notifications. There is an unknown error:

      “ExceptionType”: “System.ComponentModel.Win32Exception”,
      “StackTrace”: null

      Does anybody know how I can solve this problem? Anyone with the same problem?



  13. kassem says:

    hi all

    i am having the following error: “the credentials supplied to the package were not recognized” in “OpenSslStream” function in line:” _apnsStream.AuthenticateAsClient(host, certificates, System.Security.Authentication.SslProtocols.Ssl3, true);”

    please any help???

  14. Ananth says:

    Very helpful article. I was able to send notification in no time from my c# application. Please note that to receive notification, notification needs to be turned on for the application and the application has be in the background.

  15. Archana says:

    I tried it on localhost and its working here, As I tried it on server i got error;

    System.Security.Cryptography.CryptographicException: An internal error occurred.

    Statement where this problem generating.

    NotificationService service = new NotificationService(sandbox, p12Filename, p12FilePassword, 1);

    Could you please help to resolve this problem? Please reply ASAP

  16. chandresh kanetiya says:


    I got the following error, when sending APNS message.

    Error At 1/28/2014 12:35:09 PM
    Error Message—>An internal error occurred.
    StackTrace–> at System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr) at System.Security.Cryptography.X509Certificates.X509Utils._LoadCertFromBlob(Byte[] rawData, IntPtr password, UInt32 dwFlags, Boolean persistKeySet, SafeCertContextHandle& pCertCtx) at System.Security.Cryptography.X509Certificates.X509Certificate.LoadCertificateFromBlob(Byte[] rawData, Object password, X509KeyStorageFlags keyStorageFlags) at System.Security.Cryptography.X509Certificates.X509Certificate..ctor(Byte[] rawData, String password) at System.Security.Cryptography.X509Certificates.X509Certificate2..ctor(Byte[] rawData, String password) at MoonAPNS.PushNotification..ctor(Boolean useSandbox, String p12File, String p12FilePassword) at PushNotification.IPhone.SendNotification(String NotificationText, String ParentDeviceToken, Int32 BedgeCounter, String strP12FilePath, String strP12FilePassword) in D:\STTL projects\MyNino\MyNinoWebService\PushNotification\IPhone.cs:line 43 at ChildTracker.Helper.SendPushNotification(ParentMaster Parent, String NotificationText)

  17. Haider says:

    hi All, i applied the joseph answer given above in 3 steps, i succeeded to send push notification through development certificate, i repeat the same process to make the .p12 from the production certificate, i upload my iPhone app ipa on test flight, and start sending push notification, i get the successfully sent message string but i don’t get the push notification on my iPhone app,

    to make the .p12 for development and production ssl certificate is not the same?

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s