iOS Push Notifications in C# with Moon-APNS

I have been busy developing backend of an IPhone application which is sending considerable number of push notifications twice a day. Trying to fix some issues and bugs on other free and open source c# push notification libraries I came up with the idea of writing my own c# library and as a big fan of open source I’m going to share the library on GitHub.

The library is called Moon-APNS and it can be downloaded from here.

This is the first version of the library, but It has been tested under pressure and on a production version of an application so feel safe to plug it to you application. Moon-APNS can be used in any .net application web or windows based.

Moon-APNS is benefiting from new Apple Push Notification structure, called Enhanced Push Notification. Which enables the library to receive feedback on each notification sent to apple server asynchronously, you may say we can receive that response with apple feedback service, but unfortunately if you send a payload to apple server with wrong format, broken or missing device tokens apple will terminate the connection straight away and it’s really hard to figure out which one was the faulty payload when you are sending them one after each other because it takes up to 2 seconds for the connection to be closed. Using Enhanced push notification you can sign each payload with a unique identifier and even better you can set TTL on each payload so apple know how long they should try to deliver the push notification before it expires. Moon-APNS will send payloads and receive feedback asynchronously and will re connect and resume sending the queue in case of any errors. All device tokens of rejected payloads will return as a list when the queue is sent and feedback is received from apple with error code sent by apple so you will know why the payload was rejected.

In Moon-APNS I’m using free and open source NLog library to log all events happening behind the scene which makes it really easy to debug the application while you are on production and you can’t attach a debugger.

Sending Apple push notification has never been so easy with Moon-APNS you will need less than 10 lines of code to send push notification and receive the feedback.

Ok enough talking I think it’s time for some coding.

1) You should generate your payloads:

 1:  var payload1 = new NotificationPayload("DeviceToken","Hello !",1,"default");

Feel free to add custom parameters to your payload as bellow:

 1: payload1.AddCustom("CustomKey", "CustomValue");

2) Moon-APNS accepts a list of payloads, so I will add my payloads to a List:

 1: var notificationList = new List {payload1, payload2, payload3};

3) create an instance of Moon-APNS push notification class, and pass true or false for using sandbox, location of your p12 file, and password for thep12 file if you have one and blank string if you don’t have one.

 1: var push = new PushNotification(false, "P12File location","password");

4) Create a list for your feedback, returned from library which will contain rejected payloads list.

5) Saved best for last call SendToApple method and pass list of your payload.

 1: var rejected = push.SendToApple(notificationList);

Is that all? Well yes it is! So if we ignore lines for generating payloads I can say we are sending push notification ad receiving feedback in 2 lines of code. Everything you need to do is handled by Moon-APNS library for you so you can have more time to consider on your application logic.

Feel free to email me or post your questions as a comment and I’ll be more than happy to assist you as much as I can.

This is the first version and I will commit new builds with new features soon.

92 thoughts on “iOS Push Notifications in C# with Moon-APNS

  1. ziv says:

    Hi arashnorouzi
    First of all thank you for the code it looks great.
    i have a question, in my application i cannot control the amount of chats , the user can send when ever they want.
    which means i always create a new instance which has a list of one message and sends it , i understand that apple would prefer that i add them up a bit and then send them, lets say with a 15 second delay between connection attempt to another.
    any recommendations on how to implement that using your code ?
    Ziv

    • Hi Ziv,
      You are most welcome.
      I think it’s easier for you to check Items count in your push notification queue, For example you can:
      Crate a list of payloads, when you receive a new massage after adding it to your queue check Items count and if it was 15 call PushToApple method and pass your current queue.
      After receiving feedback, clear the list.
      I can write a sample code for you if it helps.

      • ziv says:

        Hi arashnorouzi
        I’m not sure it will work for me.
        in my application users can send each other chat messages and i cant control the stress load, if i take your suggestion for example there is a possibility that in morning time (slow traffic) there wont be 15 message for several hours which will miss the point of push and in the evening time there would be hundreds in a minute.
        i need someway to combine the 15 ( a number) with a time interval that will say OK no 15 but its waiting for a minute so I’m sending anyway.
        i was thinking maybe writing all messages to DB and every X time run a procedure that will sent them all, but its not very elegant and i would prefer doing all inside the code.
        anyway i would love to see your example to get a better feel of how you see implementation of a queue.

        thank you
        ZIv

      • Hi Ziv,
        What you need is threading. your thread will run every 15 seconds for example. If count of items in queue is larger than 20 it will send the message, if not it will sleep for another 15 seconds.
        And you will increase a number every time you count items in the queue, if its larger than 4 which means every minute and your items in list are less than 20, you will send the queue.
        I hope this helps.
        Please let me know if you need more info.
        Thanks.

  2. Clive Hoggar says:

    HI

    I am having a problem with certificates..
    I am seeing an exception error when running the code in my visual studio development environment on windows 7 machine. I have a feeling that it is just a windows setup issue. Can anyone help? I have spent many hours trying to fix this issue, and am stumped!

    Ex error follows:
    “The credentials supplied to the package were not recognized
    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

    Exception Details: System.ComponentModel.Win32Exception: The credentials supplied to the package were not recognized

    Source Error:

    Line 215: try
    Line 216: {
    Line 217: _apnsStream.AuthenticateAsClient(host, certificates, System.Security.Authentication.SslProtocols.Ssl3, false);
    Line 218: }
    Line 219: catch (System.Security.Authentication.AuthenticationException ex)

    Source File: c:\inetpub\wwwroot\MoonAPNS\App_Code\PushNotification.cs Line: 217

    Stack Trace:

    [Win32Exception (0x80004005): The credentials supplied to the package were not recognized]
    System.Net.SSPIWrapper.AcquireCredentialsHandle(SSPIInterface SecModule, String package, CredentialUse intent, SecureCredential scc) +6153980
    System.Net.Security.SecureChannel.AcquireCredentialsHandle(CredentialUse credUsage, SecureCredential& secureCredential) +280
    System.Net.Security.SecureChannel.AcquireClientCredentials(Byte[]& thumbPrint) +1108
    System.Net.Security.SecureChannel.GenerateToken(Byte[] input, Int32 offset, Int32 count, Byte[]& output) +582
    System.Net.Security.SecureChannel.NextMessage(Byte[] incoming, Int32 offset, Int32 count) +112
    System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest) +34
    System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest) +53
    System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest) +120
    System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest) +85
    System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest) +61
    System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest) +137
    System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest) +53
    System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest) +120
    System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest) +85
    System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest) +61
    System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest) +137
    System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest) +53
    System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest) +120
    System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest) +85
    System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest) +61
    System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest) +137
    System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest) +143
    System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult) +99
    System.Net.Security.SslStream.AuthenticateAsClient(String targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, Boolean checkCertificateRevocation) +47
    MoonAPNS.PushNotification.OpenSslStream(String host, X509CertificateCollection certificates) in c:\inetpub\wwwroot\MoonAPNS\App_Code\PushNotification.cs:217
    MoonAPNS.PushNotification.Connect(String host, Int32 port, X509CertificateCollection certificates) in c:\inetpub\wwwroot\MoonAPNS\App_Code\PushNotification.cs:182
    MoonAPNS.PushNotification.SendQueueToapple(IEnumerable`1 queue) in c:\inetpub\wwwroot\MoonAPNS\App_Code\PushNotification.cs:111
    MoonAPNS.PushNotification.SendToApple(List`1 queue) in c:\inetpub\wwwroot\MoonAPNS\App_Code\PushNotification.cs:84
    _Default.Page_Load(Object sender, EventArgs e) in c:\inetpub\wwwroot\MoonAPNS\Default.aspx.cs:29
    System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14
    System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35
    System.Web.UI.Control.OnLoad(EventArgs e) +91
    System.Web.UI.Control.LoadRecursive() +74
    System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2207”

    • Hi Clive,
      Just received your comment. Have you installed the certificates properly? Do you have passwords on the certificate ?
      Have you set that ?
      var push = new PushNotification(True for using production certificates or False to use sandbox, “Location of P12 file”,”password”);
      Please let me know if you could not find the problem.

      • Clive Hoggar says:

        Hi
        It seemed I needed the certificate without the key, not as advised by Apple.. now the messages are going and being received on the test phone.
        However the log shows an error message which may not matter…

        “An error occurred while reading Apple response for token xyz Safe handle has been closed”

        Is this a problem?

        Thanks

        Cive

      • Hi,

        I have .p12 file but there is not set any password on that file.so when i am connecting with APNS server then it gives error “A call to SSPI failed, see inner exception.”
        Can possible a p12 file without password?
        Please help me.

        Regards,
        Rajesh

      • Hello, i have the same problem, i am sure that the file is imported correctly, I set the password an dile location but i have the same error
        “The credentials supplied to the package were not recognized”

        in this line
        Source Error:

        Line 215: try
        Line 216: {
        Line 217: _apnsStream.AuthenticateAsClient(host, certificates, System.Security.Authentication.SslProtocols.Ssl3, false);
        Line 218: }
        Line 219: catch (System.Security.Authentication.AuthenticationException ex)
        How i can resolve this problem

      • Vikas says:

        Hi
        I am also having problem with certificate.
        having Win32 exception “The credentials supplied to the package were not recognized”.
        Below line, i am getting the crash.
        _apnsStream.AuthenticateAsClient(host, certificates, System.Security.Authentication.SslProtocols.Ssl3, false);
        Stack trace is as below:
        ————————
        > MoonAPNS.DLL!MoonAPNS.PushNotification.OpenSslStream(string host, System.Security.Cryptography.X509Certificates.X509CertificateCollection certificates) Line 232 + 0x1d bytes C#
        MoonAPNS.DLL!MoonAPNS.PushNotification.Connect(string host, int port, System.Security.Cryptography.X509Certificates.X509CertificateCollection certificates) Line 197 + 0xe bytes C#
        MoonAPNS.DLL!MoonAPNS.PushNotification.SendQueueToapple(System.Collections.Generic.IEnumerable queue) Line 126 + 0x25 bytes C#
        MoonAPNS.DLL!MoonAPNS.PushNotification.SendToApple(System.Collections.Generic.List queue) Line 99 + 0xe bytes C#
        SendToast.DLL!SendToast.SendToast.ButtonSendIOSNotification_Click(object sender, System.EventArgs e) Line 108 + 0xd bytes C#
        —————————————————————————————————- we tried with both options (having password p12 file andn non password p12 files),Same problem is coming.
        Also the certificate developed should be correct as using same we can send push notification by a sample Mac OS app.
        Could you help us to know where is the problem?

      • dp says:

        If anybody is still running into this issue…the fix is to install your .p12 cert (usually double-clicking on it) and then export it making sure you uncheck the option to include the key. This goes for both windows and macs.

  3. Clive Hoggar says:

    Thanks for this great apns library by the way.

    Further to my Post about ‘Safe handle has been closed’:
    I am baffled by the the full exception error at that point which is…

    System.ObjectDisposedException: Safe handle has been closed
    at System.Runtime.InteropServices.SafeHandle.DangerousAddRef(Boolean& success)
    at System.StubHelpers.StubHelpers.SafeHandleAddRef(SafeHandle pHandle, Boolean& success)
    at System.Net.UnsafeNclNativeMethods.OSSOCK.setsockopt(SafeCloseSocket socketHandle, SocketOptionLevel optionLevel, SocketOptionName optionName, Int32& optionValue, Int32 optionLength)
    at System.Net.Sockets.Socket.SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, Int32 optionValue, Boolean silent)
    at System.Net.Sockets.NetworkStream.SetSocketTimeoutOption(SocketShutdown mode, Int32 timeout, Boolean silent)
    at System.Net.Sockets.NetworkStream.set_ReadTimeout(Int32 value)
    at System.Net.Security.SslStream.set_ReadTimeout(Int32 value)
    at MoonAPNS.PushNotification.ReadResponse(IAsyncResult ar) in c:\inetpub\wwwroot\xxxx\App_Code\CSCode\PushNotification.cs:line 147

    Can you suggest where to look for the problem?

    Thanks a million

    Clive

  4. Sejong says:

    Hi arashnorouzi.

    Thank you so much for this beautiful library. I could easily develop provider server with this library.

    By the way, I have a question.

    If I use Non-English language for ‘alert’ when creating payload, it seems to be sent to the Apple but nothing happens to my device, while it does work if I use English.

    Do you have any idea of why? And can you suggest how to solve it?

    • Hi Sejong,
      I’m really happy that Moon-APNS is useful for you.
      As much as I know, you can send custom localized text to be shown on your buttons when the push notification is shown on the device.
      But I have never tried to send non English push notifications. I would be thankful if yo share your results with us as well.

      • Sejong says:

        I have sold the problem.

        On line 296 in ‘PushNotification.cs’ file, I have modified your code as follows..

        // String length
        byte[] apnMessageLength = BitConverter.GetBytes((Int16)Encoding.UTF8.GetBytes(apnMessage).Length);

        and on line 305 was modified as

        // Write the message
        memoryStream.Write(Encoding.UTF8.GetBytes(apnMessage), 0, Encoding.UTF8.GetBytes(apnMessage).Length);

        At first, I just replaced ‘ASCII’ to ‘UTF8’ on line 305, and my push alert text broken; It showed just question marks like ‘?????’.
        The problem was that UTF8 takes 3bytes(maybe 2bytes? whatever..) per a character while ASCII takes 1byte. So I worked on line 296 as above and it worked fine!:)

        Thanks.

  5. Hi
    I am using this excellent code in the asp.net webservice for a new iPhone app.
    All is working well in our live testing but would now like to make use of the ability to add custom items to the payload.

    I am going through a ‘push list’ from a database like this:

    ============== code =============

    Dim p = New List(Of NotificationPayload)

    ‘ build push list

    while rdr.Read()
    strToken = rdr(“Token”)
    strMsg = rdr(“Message”)
    badgenumber = rdr(“BadgeNumber”)
    alertsound = rdr(“AlertSound”)
    strUserID = rdr(“userID”)

    ‘ add new payload item

    p.Add(New NotificationPayload(strToken, strMsg, badgeNumber, alertsound))

    ‘ here I would like to add, for example, AddCustom(“UserID”, strUserID) to this payload item

    End While
    ============= end of code===========

    Since I am not adding the payloads as individual objects such as payload1, payload2, etc , I can’t figure out the syntax to add the custom items. Can you advise?

    Thanks a lot

    Clive

    • Nick Chadwick says:

      payload = New NotificationPayload(strToken, strMsg, badgeNumber, alertsound)
      payload.AddCustom(“UserID”, strUserID)
      p.Add(payload)

    • sunil says:

      Hello ,

      I am getting the following response after the process (from APNS server) :-

      5/31/2012 6:13:23 PM—Payload queue received.
      ————————————————————————-
      5/31/2012 6:13:24 PM—Connecting to apple server.
      ————————————————————————-
      5/31/2012 6:13:25 PM—Creating SSL connection.
      ————————————————————————-
      5/31/2012 6:13:26 PM—Conected.
      ————————————————————————-
      5/31/2012 6:13:27 PM—Payload generated for cd6daa9e5bdb7516f6c1b94f6f146515d3ec39ec9be56a4c3a372b10b9db9632 : {“aps”:{“alert”:”new sipl testing”,”badge”:1,”sound”:”defualt”}}
      ————————————————————————-
      5/31/2012 6:13:27 PM—Notification successfully sent to APNS server for Device Toekn : cd6daa9e5bdb7516f6c1b94f6f146515d3ec39ec9be56a4c3a372b10b9db9632
      ————————————————————————-
      5/31/2012 6:13:28 PM—Apple rejected palyload for device token : cd6daa9e5bdb7516f6c1b94f6f146515d3ec39ec9be56a4c3a372b10b9db9632
      ————————————————————————-
      5/31/2012 6:13:29 PM—Apple Error code : Invalid token
      ————————————————————————-
      5/31/2012 6:13:29 PM—Invalid device token length, possible simulator entry: cd6daa9e5bdb7516f6c1b94f6f146515d3ec39ec9be56a4c3a372b10b9db9632
      ————————————————————————-
      5/31/2012 6:13:30 PM—Connection terminated by Apple.
      ————————————————————————-
      5/31/2012 6:13:31 PM—Disconnected.

      Here is the details of my code :-

      1) On this i used this device token :

      cd6daa9e5bdb7516f6c1b94f6f146515d3ec39ec9be56a4c3a372b10b9db9632

      2) I am using .p12 file that is included in my web service project (asp.net)

      3) And currently i have no SSL certificate and i am testing this on my local machine.

      I did not uploaded this Push Notification code on my hosting server.

      >> Please give me the whole detail about the following response that i got from APNS server and about the SSL certificate (using and installation on server).

      Thanks

  6. check says:

    Hello,
    I am Getting this Error in this line
    _apnsStream.AuthenticateAsClient(host, certificates, System.Security.Authentication.SslProtocols.Ssl3, false);
    A call to SSPI failed, see inner exception.
    Under this Getting
    “System.Object Disposed Exception Cant Access a close file “

  7. Blackwaltz says:

    Hi arashnorouzi
    Thanks for your introduce of this tool.
    I downloaded project from this page
    “https://github.com/arashnorouzi/Moon-APNS/downloads”
    but I can`t rebuild it or use any dll in the project because the error message shows :
    Can not find the referenced component ‘Newtonsoft.Json’
    Can not find the referenced component ‘NLog’
    Can not find the referenced component ‘Microsoft.CSharp’

    Do you have any suggestion about this error? Thanks a lot!

  8. Walter says:

    Dear arashnorouzi

    thank you so much for Moon-APNS.

    I have downloaded it and tested it using .Net 4.0 and it works perfectly. Thanks.

    Unfortunately, the project which I would like to use it in is written in .Net 3.5. I have tried to switch the target framework to 3.5 and to re-build the project but it fails.

    I’m getting the following error messages for Newtonsoft, NLog and Logger:

    The type or namespace name ‘Newtonsoft’ could not be found (are you missing a using directive or an assembly reference?)

    Do you have a release of Moon-APNS for .Net 3.5 which I could download please.

    Kind Regards

    Walter

  9. Hi arashnorouzi,
    Thanx a lot for your great API. I could easily send push notifications to my IPhone from my windows app. I just have one concern. The NSLog is not working, ie., I am not able to fine any log files in the configured directory. I changed the log directory to a new one that i created withing the project directory itself, from the one which was out of the project (the one u had created). I have also changed the log’s path in the config file. Still I dont see a change. Please guide me on this.
    Thanks a lot,
    Ananth

  10. Gaurav says:

    Hi,
    I m trying to use it in my project and it gives me following error (e.g. from NLog text file) :
    Invalid device token length, possible simulator entry:

  11. Rasam says:

    Hi Arash,

    Thank you for posting this code. I am running into an issue which I have not been able to resolve. I have built ur project and have referenced it in my project. I then transfered it into my dev server. The issue I am seeing is that I do not get a success or fail message and nothing is delivered to the phone. I was wondering if you had ran into this situation. Thanks, Rasam

  12. Hi arashnorouzi.

    First of all, thank you for this brilliant library.

    I was able to send push notification with prodocution certificate to my devices.

    However, i couldn’t manage to receive any data with GetFeedBack() method.
    recd = _apnsStream.Read(buffer, 0, buffer.Length); returns 0.

    Can you suggest where to look for the problem?

    Thanks in advance,

    Joe

  13. Michael Bourgoin says:

    what do you mean by p12 file location? is it the virtual location where we installed it or it’s the physical location on the drive?

    Thanks

    Mike

  14. hunter says:

    Hey arashnorouzi, thank you for this great library.
    I have a problem.
    I’ve sent 1000 payloads with 800 invalid tokens and
    var rejected = push.SendToApple(payloadList); returns only a few of the invalid tokens.
    I assume that when i send invalid token APNS closes the connection for couple of seconds. Even if i set the Thread.Sleep(5000); i couldn’t get the correct number(800) as rejected. Do you have any suggestions?

    Thanks in advance.

  15. Cafe Coder says:

    > “An error occurred while reading Apple response for token xyz Safe handle has been closed”

    After hours of looking into this error as well I have come to the following conclusions. My use case is +100,000 messages sent a time. First thing I need to do was remove the Thread.Sleep(1000), otherwise it waits one second per message. The code comment said we have to wait. I don’t think so as it would defeat the purpose of async.

    The error is being thrown because of Disconnect being called before the stream has been properly shut down.

    Thanks to this link I also learned the ReadCall back is only called when the connection is disconnected not while the connection is open reading and writing.
    http://robjdavey.wordpress.com/2011/02/12/asynchronous-tcp-server-example/

    Same applied when I tested on MSDN’s example:
    http://msdn.microsoft.com/en-us/library/system.net.security.sslstream.beginread.aspx

    Love this lib, but needs to be upgraded to handle the needs of high volume senders. I am going to hack it for now, and if I can get it to a stable state I will share the code.

    Hope that helps take the mystery out of it.

  16. Ronen says:

    hi, thanks for the api, maybe i don’t use it right, but right now you have a line there for sleeping the thread for one second after each sending of notification. This cause a process of sending many messages to last for too long time to be useful. I don’t see how the asynchronous behavior happens here. It happens in the following code:
    private void SendQueueToapple(IEnumerable queue)
    {
    int i = 1000;
    foreach (var item in queue)
    {
    if (!_conected)
    {
    Connect(_host, NotificationPort, _certificates);
    var response = new byte[6];
    _apnsStream.BeginRead(response, 0, 6, ReadResponse, new MyAsyncInfo(response, _apnsStream));
    }
    try
    {
    if (item.DeviceToken.Length == 64) //check lenght of device token, if its shorter or longer stop generating Payload.
    {
    item.PayloadId = i;
    byte[] payload = GeneratePayload(item);
    _apnsStream.Write(payload);
    Logger.Info(“Notification successfully sent to APNS server for Device Toekn : ” + item.DeviceToken);
    Thread.Sleep(1000); //Wait to get the response from apple.
    }
    else
    Logger.Error(“Invalid device token length, possible simulator entry: ” + item.DeviceToken);
    }
    catch (Exception ex)
    {
    Logger.Error(“An error occurred on sending payload for device token {0} – {1}”, item.DeviceToken, ex.Message);
    _conected = false;
    }
    i++;
    }
    }

  17. abhiji says:

    Hi ,
    I using MoonAPN dll for push notification Iphone(asp.net web app using MoonAPN.dll),
    I have sucessfully added the certificates and by using dll it working fine on the local machine,
    but after deployment it will give the erorr,

    ” Could not load the assembly ‘MoonAPNS’ or one of its dependency.An attempt was made to load program with an incorrect format incorrect”.

    even I follow certification installation procedure.
    (server Os is sever 2008)
    Plase give reply ASAP
    its Urgent

    Million Thanks in Advance

    Abhijeet.

  18. Thanks for creating and sharing MoonAPNS!!!

    When I run the console app (Program.cs) I see a black console window open, no exceptions are thrown, but no notification is sent to my device. To troubleshoot this, I’m hoping you have time to quickly review my changes to your Main() in Program.cs. I’m simply trying to do a ‘hello world’ test right now.

    Question: In Program.cs in Main do I need to change the “Device token” hard-coded string? If so, how do I know what the device token is from my user? Doesn’t this change over time?
    Question: Can you quickly review the few lines of code in my Main() function and inform me if I need to change any of the other parameters to NotificationPayload() or PushNotifications() methods?

    private static void Main(string[] args)
    {
    var payload1 = new NotificationPayload(“Device token”,”Hello”, 1,”Sound”);

    var p = new List {payload1};

    var push = new PushNotification(false, “C:\\ApplePushNotification_SSLCerts\\DevelopmentCerts\\Certificates.p12”, “p@ss*1”);

    var rejected = push.SendToApple(p);
    foreach (var item in rejected)
    {
    Console.WriteLine(item);
    }
    Console.ReadLine();
    }

    Thanks again for sharing this!!!

  19. Jose says:

    Hello I don’t know what values I have to put in this line of code:
    payload1.AddCustom(“CustomKey”, “CustomValue”);

    CustomKey ? what does it mean?

    Thanks

  20. nbl says:

    I get an error. “The credentials supplied to the package were wrong”. I have given the password that I used to import the certificate into the system..

    Error is at this line:
    _apnsStream.AuthenticateAsClient(…) in the OpenSslStream method in the PushNotification class.

    while importing the certificate and P12 file in MMC to the personal certificates section I can go thru smoothly, but when trying the same for the ” Trusted Root Certification Authorities ” Section, I get an error from the console “The import failed because the store was read only, the store was full or the store did not open correctly”

    Any idea on how to fix these problems?

  21. kiran ugale says:

    Hi, have following problem while sending push notification from c# to iOS device.
    please help me.
    Error is:-
    A first chance exception of type ‘System.FormatException’ occurred in mscorlib.dll
    A first chance exception of type ‘System.NullReferenceException’ occurred in System.dll
    The thread ‘vshost.RunParkingWindow’ (0x928) has exited with code 0 (0x0).
    The thread ” (0x880) has exited with code 0 (0x0).
    The program ‘[1232] PushDemoMoonApnsWindows.vshost.exe: Program Trace’ has exited with code 0 (0x0).
    The program ‘[1232] PushDemoMoonApnsWindows.vshost.exe: Managed (v4.0.30319)’ has exited with code 0 (0x0).

  22. Luke says:

    I downloaded your code but was never able to get it going – so i used the code as a guide to implement my own much more basic push notification processing in my vb.net app.

    I am confused about this peice of code in the SendQueueToapple function in PushNotification.cs;

    _apnsStream.Write(payload);
    Logger.Info(“Notification successfully sent to APNS server for Device Toekn : ” + item.DeviceToken);
    Thread.Sleep(1000); //Wait to get the response from apple.

    It seems like there will be a one second delay for each notification sent. So if i send 20 in the queue, 20 seconds of processing time will be spent sleeping? Is there no way to send batches to avoid long delays?

  23. Thank you for your great contribution to the community. I am trying to set up a server which will push one single notification to all registered devices (for emergency weather alerts, etc), would you recommend using your method with a database of all registered devices and looping through all of them to send them or do you know of a better approach to doing this?

    Thank you!

    Ham

  24. miles says:

    I’m trying to use this library and have it working on a local machine but am having difficulties in putting it into a shared hosting environment.

    Two questions:
    Is it absolutely necessary to use MMC and install on the machine? (I’m guessing that this is the problem that I’m currently having but don’t know for sure)
    How do I enable the logging so that I can view what is happening in the logs and see what is going on with the remote machine?

    Thanks so much!

  25. yYy says:

    Hi , thanks for this great project

    I have question about Thread.Sleep(1000). In SendQueueToapple methot there is a line for sleeping threat for each push request. Is this line necessary because if i send a 600 not. at the same time. It will takes 10 minute to send.

    Thanks

  26. sunil says:

    Hello ,

    I got below response from APNS server :

    5/31/2012 6:13:23 PM—Payload queue received.
    ————————————————————————-
    5/31/2012 6:13:24 PM—Connecting to apple server.
    ————————————————————————-
    5/31/2012 6:13:25 PM—Creating SSL connection.
    ————————————————————————-
    5/31/2012 6:13:26 PM—Conected.
    ————————————————————————-
    5/31/2012 6:13:27 PM—Payload generated for cd6daa9e5bdb7516f6c1b94f6f146515d3ec39ec9be56a4c3a372b10b9db9632 : {“aps”:{“alert”:”new sipl testing”,”badge”:1,”sound”:”defualt”}}
    ————————————————————————-
    5/31/2012 6:13:27 PM—Notification successfully sent to APNS server for Device Toekn : cd6daa9e5bdb7516f6c1b94f6f146515d3ec39ec9be56a4c3a372b10b9db9632
    ————————————————————————-
    5/31/2012 6:13:28 PM—Apple rejected palyload for device token : cd6daa9e5bdb7516f6c1b94f6f146515d3ec39ec9be56a4c3a372b10b9db9632
    ————————————————————————-
    5/31/2012 6:13:29 PM—Apple Error code : Invalid token
    ————————————————————————-
    5/31/2012 6:13:29 PM—Invalid device token length, possible simulator entry: cd6daa9e5bdb7516f6c1b94f6f146515d3ec39ec9be56a4c3a372b10b9db9632
    ————————————————————————-
    5/31/2012 6:13:30 PM—Connection terminated by Apple.
    ————————————————————————-
    5/31/2012 6:13:31 PM—Disconnected.

    please let me know what i need to do for fix this issue.

    Thanks,
    Sunil

  27. sunil says:

    i am getting this error when i uploaded the push notification code to my hosting server :-
    “System.Security.Permissions.KeyContainerPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089′ failed.”

    please let me know what is the issue ?

  28. Hi,

    First of all thanks a lot for providing push notification code.
    Currently I am using your code and i find out that I am getting error in NLog file that Input String was not in a correct format.

    Do you know how do i resolve this error?

    Thanks.

    • Rajendra says:

      create object for PushNotification like this
      var push = new PushNotification(true, ‘p12 file path’, ‘p12 password’);
      Set first parameter to to TRUE

  29. Hi,
    I am getting below error.
    A call to SSPI failed, see inner exception. and inner exception is “An unknown error occurred while processing the certificate”
    I dont understand whats goes wrong.
    I have registered .cer and .p12 files in personal and Trusted Root section.

    Can you please help.

    Thanks in advance.
    Vijay

  30. Hi arashnorouzi,
    Thank you for a great app. I tried you code and followed all your steps. Code worked fine without any issues.
    But I have not received any alert or notification.
    Will there time consumed for notifications?

    Here is my code

    var payLoad1 = new NotificationPayload(“my udid”, “Hello !”, 1, “default”);
    payLoad1.AddCustom(“R1”, “Test Value”);

    var notificationList = new List(){ payLoad1};
    var push = new PushNotification(false, Server.MapPath(“~\\Certificates\\Certificates.p12”), “abcd@654321”);
    var rejected = push.SendToApple(notificationList);

    Kindly help me. Let me know if I am missing any thing else.
    Thanks in advance

  31. Works great, code is clean and well done, outstanding job you’ve done Sir!

    I’m facing an issue commented here before “Safe Handle was closed” Is there something I’ve done incorrectly? anyone knows what to do with that?

    More specifically: Safe handle has been closed

  32. Tango says:

    Hi

    I tried to use yr code to check for Invalid deviceToken, not sure how it work.

    I used yr code to send Push Notifications and my ipad received it, I uninstall the app and run yr code again, it did not catch this deviceToken as invalid

    Thanks.

  33. Shishir says:

    hello!
    Firstly thanks for your nice share!!

    Locally my code run well. Also in IIS it’s running totally Ok. But uploading to ftp it doesn’t work! It is giving an exception stating ” A call to SSPI failed, see inner exception.\nInnerException: System.ComponentModel.Win32Exception (0x80004005): The message received was unexpected or badly formatted ” It’s facing the problem to encode the certification file of iOS App ( .p12 file)
    While converting the certification file using X509Certificate2, it’s giving the exception! It’s working on local IIS perfectly but not after uploading to host! Here id my URL which I have been trying to make call : http://www.createplaydate.com.asp1-21.ord1-1.websitetestlink.com/api/PushNotificationIOS/SendPushNotification Waiting to hear you soon!
    Thanks in advanced again!
    Regards
    Shishir

  34. Looks like Github sources include binaries which are uncompatible with 64-bit AppPool version. So, it did help to use 32-version, but not such a good way to use modern technologies. If 64-bit version used, then “Could not load file or assembly ‘MoonAPNS’ or one of its dependencies.” “yellow” IIS page shown.

  35. Tarun Parihar says:

    Hi,

    Very helpful and easy to use lib.
    I am facing some problem using this, I had done all the certificates correctly checked with a dummy project on MAC I am getting the push notification but as soon as I move to ASP.net it runs without error but in in function “ReadResponse” I am getting all bytes as 0 and here I am getting error while encoding plus I am not getting the notification on my phone. I have been struggling with this for a long time now, little help is really appreciated
    thanks
    Tarun Parihar

  36. Tarun says:

    Hi,
    That’s excellent lib,
    But I am facing some issues while sending it to apple server.
    My AppID is okay my certificates are also okay tested with one of the demo MAC code, phone did recvd the push notification.
    While I am trying to send the push notification from local server it is not happening, it returns 0 in all bytes and I am not able to recv the push notification.
    A little help would be appriciated
    Thanks

  37. Harshada says:

    Hi,
    Thanks for your code.
    I created console App and followed your code. I am getting folloeing exception
    “An unknown error occurred while processing the certificate”

  38. Vikash says:

    Hi,

    We are also trying to use MOON-APNS and its working fine at the time of debugging but we are trying to run the same application on the server after keeping the p12 file
    C:\Windows\System32\inetsrv folder its giving following error.

    An internal error occurred. Value cannot be null. Parameter name: value

    Please Suggest Us.

  39. thanks for your Code
    but i have a problem
    moon apns library working fine for Development cert but did not send notification when using Production Certificate. What can i do please suggest

  40. Gurinder says:

    Getting error in this line:

    payLoadIndex = ((int.Parse(payLoadId)) – 1000);

    20130220 1609 – Info – Payload queue received.
    20130220 1609 – Info – Connecting to apple server.
    20130220 1609 – Info – Creating SSL connection.
    20130220 1609 – Info – Conected.
    20130220 1609 – Info – Payload generated for cac7ff296a303588024479623609f7deda2f058ee3b6cf29ae5f9ad01d2f3d15 : {“aps”:{“alert”:”Message1″,”badge”:1,”sound”:”default”}}
    20130220 1609 – Info – Notification successfully sent to APNS server for Device Toekn : cac7ff296a303588024479623609f7deda2f058ee3b6cf29ae5f9ad01d2f3d15
    20130220 1609 – Error – An error occurred while reading Apple response for token cac7ff296a303588024479623609f7deda2f058ee3b6cf29ae5f9ad01d2f3d15 – Input string was not in a correct format.

  41. sbs says:

    I am using the MoonAPNS to implement Push Notification on iOS devices. Everything works fine. However, I came across this in Apple’s Documentation –

    “You should also retain connections with APNs across multiple notifications. APNs may consider connections that are rapidly and repeatedly established and torn down as a denial-of-service attack.”

    I see that instantiating the PushNotification Class of MoonAPNS creates a new connection every time. Has anybody solved this issue and maintained a single Connection to the APNS for a specified time? Should I implement the Singleton Pattern and instantiate the PushNotification Object only once?

  42. First of all thank you very much for this great code, but I have got an issue about the Asynctask operation “ReadResponse”. I get a SystemFormatException because info.ByteArray[6] filled with zeros or never filled. I suspect this is because a non-received response. Any idea how to fix that? Thank you

  43. Mathew says:

    I am encountering a strange problem sending push notiifcations to iPhones from my asp.net website
    Push notiifcations when sent from the website root are not received on the phone.

    When the files that are in the root of the website are copied to a subfolder on the same site(set as an application) and push notifications are sent they are received successfully .

    What could be the problem?

    regards

    Mathew

  44. Hi, I’m getting an error message “A call to SSPI failed, see inner exception.” while executing _apnsStream.AuthenticateAsClient, inside the OpenSslStream method.

    Since it’s inside in a try/catch section, afterwards, when it tries to execute _apnsStream.BeginRead it produces an innerexeption “uknown error while processing the certified”

    Could you please help me out to figure out what’s the problem?

  45. Sachin Yadav says:

    How to get the list of device Token for which notification haven’t sent successfully. I tried the GetFeedback method but it returns empty response even when there is one invalid device token present. I also test with push.SendToApple method which may be returns rejected token but it also returns black even if there is an invalid token present. So please let me know, how to get the list of token for them message didn’t send successfully.

  46. subramanya says:

    Hi,

    i am not getting any notifications on the device, even after getting the successful response.

    After executing the sslstream.beginread am getting the response as 0. i.e., return value is successfull.

    Please help me on this.

    Thanks in advance…

  47. Prakash says:

    Hi.. I am trying to set a Push notification for my iPad and I have provided the device token, using the sand box account and the execution of the code is fine with no errors and still I am not able to get the notifications in my iPad. Can you please help me out to know what would I have missed.

    Thanks In Advance.

  48. Jey says:

    i got this following error while using apple push notification,

    “The message received was unexpected or badly formatted”
    inner exception : The message received was unexpected or badly formatted

    Any one can help me to solve this.

    Thanks in advance,
    Jey

  49. Mitesh says:

    Hi arashnorouzi

    i am mitesh.

    your code is running successfully but only one confusion is that no notification in comes in my ipad device. so can you please help me .

    i put all the code what i do in my test application. ii didnt get any error but i didnt get any notification on my device.

    ///////////////////////////////////////////////////////
    var payload1 = new NotificationPayload(“1e8ce4ff656………”, “Test Message.”, 1, “default”);
    var p = new List { payload1 };

    var push = new PushNotification(false, @”D:\\IOS\\production.p12″, “”);
    var rejected = push.SendToApple(p);
    foreach (var item in rejected)
    {
    Console.WriteLine(item);
    }
    Console.Read();

    /////////////////////////////////////////////////////////////

    one more question is what is the meaning of payload1.AddCustom(” key”,”value “);
    & how could we know that our message is successfully deleverd to apns server..

    thanks and regards

    Mitesh

  50. Oleg says:

    Hello, I’m having hard times with APNS. From time to time APNs closes connection without any bytes available for me to read. Normally I should infer a notification id from response which caused the problem but i cant, cause I cant read a byte. Any ideas what to do?

  51. One thing that seems to be a common theme reading the comments is Moon-APNS throwing the following exception: “Safe handle has been closed”.

    After posting the following question on stackoverflow.com asking about the same error:
    http://stackoverflow.com/questions/25431987/safe-handle-has-been-closed-moon-apns

    It seems the culprit is the following line of code in the PushNotification.cs class in the SendQueueToapple method:

    _apnsStream.BeginRead(response, 0, 6, ReadResponse, new MyAsyncInfo(response, _apnsStream));

    In the questions comments, it person was wondering why I was attempting to read error responses from a socket that I just opened. According to him it would never return anything. He suggested that I only attempt to read error responses from a socket when I have sent the push notification.

    When I put the code after _apnsStream.Write(payload) which I would assume is where the push notification is sent to Apple, it throws the same error.

    Have you experience this issue and were you able to resolve it?

  52. hi,

    i am trying to use this but last time it was working fine but now its giving one error in :
    _apnsStream = new SslStream(_apnsClient.GetStream(), false, validateServerCertificate, SelectLocalCertificate);

    the error is : the operation is not allowed on non-connected sockets. c#

    please give me any clue why its coming..

  53. bo huang says:

    It’s my first time on APNS.
    I’ve request a .cer from apple dev center, and exported a .p12 from keychain.
    and I imported into my win7 computer, then write a winform c# app, using moon apns library.
    After I send a message via moon apns libarary, the log said it sent succeeded.
    But my device hasn’t receive the notification message.

    No error message in the whole procedure.

    Need help!

    By the way, the device token output by my ios app is:
    shall I change it to ec3efd790cd2ebcf5506783520b65040e04253d908a8771d06e336ba0ee1397b , Revert the byte order?
    I’ve test with both 3eec79fdd20ccfeb06553578b620405042e0d953a8081d77e306ba36e10e7b39 and
    ec3efd790cd2ebcf5506783520b65040e04253d908a8771d06e336ba0ee1397b.
    Thanks a lot.

  54. Saravana Kumar says:

    Hi,
    Thank you very much for providing this wonderful project. It is working perfectly.

    Is there any possible way to send batch notifications instead of sending one by one?

    Please help me on this.

  55. Cuong Phan says:

    Hi arashnorouzi, it’s my first time on APNS. I get an exception on .p12 file:

    [CryptographicException: The system cannot find the file specified.]

    Stack trace :
    System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr) +41
    System.Security.Cryptography.X509Certificates.X509Utils._LoadCertFromBlob(Byte[] rawData, IntPtr password, UInt32 dwFlags, Boolean persistKeySet, SafeCertContextHandle& pCertCtx) +0
    System.Security.Cryptography.X509Certificates.X509Certificate.LoadCertificateFromBlob(Byte[] rawData, Object password, X509KeyStorageFlags keyStorageFlags) +230
    System.Security.Cryptography.X509Certificates.X509Certificate2..ctor(Byte[] rawData, String password) +137
    IOS.NotificationPusher.Infrastructure.MoonAPNS.PushNotification..ctor(Boolean useSandbox, String p12File, String p12FilePassword) +461
    IOS.NotificationPusher.Handlers.NotificationPusher.ProcessRequest(HttpContext context) +733
    System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +508
    System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +92

    I’ve installed the .p12 and .cer files on my server as your part3 tutorial. In this part, I copy the .p12 to my project and point this p12 file to this location.

    var p12Location = context.Server.MapPath(“~/cer/pushtest.p12”);
    var push = new PushNotification(true, p12Location, KeyFilePassword);
    var rejected = push.SendToApple(queue);

    Need help! Thanks a lot.

Leave a reply to Abraham Vivas (@abrahamvivas) Cancel reply