Send push notification on Apple (APNS) on c#.net

原文: http://apns-c-sharp-net-vikram-jain.blogspot.com

=======================
Please, Install your certificate *.p12 on pc, and take firend name use here for refernce.
Please, set configuration file :

 <appSettings>
 <add key="FriendName" value="Apple Production IOS Push Services: com.ABC.XYZ"/>
    <add key="ProductionKeyFriendName" value="Production"/>
  </appSettings>
==============
Send, push as per below in your class to call apns class:
   Cls_APNS _Cls_APNS = new class_apns();
  //Here pass custom fiels as per seprated by ";" ann asssigb value by "key=value;key=value"
   _Cls_APNS.PushMessage("Message","DeviceToken",0,"id=12;name=ABC");
==================
Please create a class as per below (class_apns.cs). :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Configuration;
using System.Data;
using System.Security.Authentication;
using System.IO;

namespace Push.Class
{
    public class class_apns
    {
        String CertificateName = "";
        String CertificatePwd = "";
        String FriendName = "Apple Development IOS Push Services: com.ABC.XYZ";
        String ProductionKeyFriendName = "Production";
        SslStream sslStream;     

        public Cls_APNS()
        {
            FriendName = ConfigurationManager.AppSettings["FriendName"].ToString();
            ProductionKeyFriendName = ConfigurationManager.AppSettings["ProductionKeyFriendName"].ToString();
        }

        public bool ConnectToAPNS()
        {
            X509Certificate2Collection certs = new X509Certificate2Collection();

            // Add the Apple cert to our collection
            certs.Add(getServerCert());

            // Apple development server address
            string apsHost;

            if (getServerCert().ToString().Contains(ProductionKeyFriendName))
                apsHost = "gateway.push.apple.com";
            else
                apsHost = "gateway.sandbox.push.apple.com";

            // Create a TCP socket connection to the Apple server on port 2195
            TcpClient tcpClient = new TcpClient(apsHost, 2195);

            // Create a new SSL stream over the connection
            sslStream = new SslStream(tcpClient.GetStream());

            // Authenticate using the Apple cert
            sslStream.AuthenticateAsClient(apsHost, certs, SslProtocols.Default, false);

            //PushMessage();

            return true;
        }

        private X509Certificate getServerCert()
        {
            X509Certificate test = new X509Certificate();

            //Open the cert store on local machine
            X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);

            if (store != null)
            {
                // store exists, so open it and search through the certs for the Apple Cert
                store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);
                X509Certificate2Collection certs = store.Certificates;

                if (certs.Count > 0)
                {
                    int i;
                    for (i = 0; i < certs.Count; i++)
                    {
                        X509Certificate2 cert = certs[i];

                        if (cert.FriendlyName.Contains(FriendName))
                        {
                            //Cert found, so return it.
                            return certs[i];
                        }
                    }
                }
                return test;
            }
            return test;
        }

        private  byte[] HexToData(string hexString)
        {
            if (hexString == null)
                return null;

            if (hexString.Length % 2 == 1)
                hexString = ‘0‘ + hexString; // Up to you whether to pad the first or last byte

            byte[] data = new byte[hexString.Length / 2];

            for (int i = 0; i < data.Length; i++)
                data[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);

            return data;
        }

        public bool PushMessage(string Mess, string DeviceToken, int Badge, string Custom_Field)
        {
            ConnectToAPNS();
            List<string> Key_Value_Custom_Field = new List<string>();
            String cToken = DeviceToken;
            String cAlert = Mess;
            int iBadge = Badge;

            // Ready to create the push notification
            byte[] buf = new byte[256];
            MemoryStream ms = new MemoryStream();
            BinaryWriter bw = new BinaryWriter(ms);
            bw.Write(new byte[] { 0, 0, 32 });

            byte[] deviceToken = HexToData(cToken);
            bw.Write(deviceToken);

            bw.Write((byte)0);

            // Create the APNS payload - new.caf is an audio file saved in the application bundle on the device
            string msg = "";
           msg = "{\"aps\":{\"alert\":\"" + cAlert + "\",\"badge\":\"" + iBadge.ToString() + "\",\"sound\":\"noti.aiff\"}";

            String PayloadMess = "";
            if (string.IsNullOrWhiteSpace(Custom_Field) == false)
            {
                List<string> list_Custom_Field = Custom_Field.Split(‘;‘).ToList();

                if (list_Custom_Field.Count > 0)
                {
                    for (int indx = 0; indx < list_Custom_Field.Count; indx++)
                    {
                        Key_Value_Custom_Field = list_Custom_Field[indx].Split(‘=‘).ToList();
                        if (Key_Value_Custom_Field.Count > 1)
                        {
                            if (PayloadMess != "") PayloadMess += ", ";
                            PayloadMess += "\"" + Key_Value_Custom_Field[0].ToString() + "\":\"" + Key_Value_Custom_Field[1].ToString() + "\"";
                        }
                    }
                }
            }

            if (PayloadMess != "")
            {
                msg += ", " + PayloadMess;
            }
            msg += "}";

            // Write the data out to the stream
            bw.Write((byte)msg.Length);
            bw.Write(msg.ToCharArray());
            bw.Flush();

            if (sslStream != null)
            {
                sslStream.Write(ms.ToArray());
                return true;
            }

            return false;
        }   

    }
}
时间: 2024-12-16 03:13:14

Send push notification on Apple (APNS) on c#.net的相关文章

Send Push Notifications to iOS Devices using Xcode 8 and Swift 3, APNs Auth Key

Send Push Notifications to iOS Devices using Xcode 8 and Swift 3 OCT 6, 2016 Push notifications are a great way to ensure your users re-engage with your app every once in a while, but implementing them on iOS can be challenging, especially with all o

iOS 8 Apple Push Notification Service

Apple Configuration 1. create Apple ID in Apple Developer Website 2. check on "Push Notification" in the functionality 3. configure for Push Notification in Development: create certificate 3.1 upload the certificate file which is generated by ke

iOS上简单推送通知(Push Notification)的实现

http://blog.csdn.net/daydreamingboy/article/details/7977098 iOS上简单推送通知(Push Notification)的实现 根据这篇很好的教程(http://www.raywenderlich.com/3443/apple-push-notification-services-tutorial-part-12),结合自己的实践,写下一点笔记,仅供参考:) 由于篇幅较长,我列出简单的目录,如下 1) 理解Apple推送通知的机制 2)

iOS推送通知(Push Notification)的Erlang实现

本文来自:瑞仙的Erlang开发博客 原文链接:http://blog.csdn.net/zhongruixian/article/details/39528765 一.前言 关于cer/pem证书转换,网上很多资料,我这就不说了, 网上有PHP实现的Push Notification,可以参考, 为了更好的做PUSH服务定制,我这里以Erlang(gen_server)实现iOS Push Notification 二.协议 1.协议分析 表1 名称 长度 描述 Command 1 字节 固定

在mac上配置push notification的问题

在代码的deletegater中写: - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; // Override point for customization after

资料整理:基于node push server实现push notification

chat example based on ionic/ socket.io/ redis https://github.com/jbavari/ionic-socket.io-redis-chat http://jbavari.github.io/blog/2014/06/17/building-a-chat-client-with-ionic/ socket.io example: http://socket.io/get-started/chat/ how node.js interact

Mobile Push Notification

In one embodiment, a method includes sending to a mobile client computing device a first notification through a real-time push service, the first notification including content and being associated with a stateful object; the method also includes, in

&quot;Missing Push Notification Entitlement&quot;警告-----以及解决方法

最近开发的cordova应用,要做ios的适配,并且发布版本,但是有一次在发测试版本的时候,突然收到一封邮件警告,原文如下: Missing Push Notification Entitlement - Your app appears to include API used to register with the Apple Push Notification service, but the app signature’s entitlements do not include the

如何在Ubuntu QML应用中使用Push Notification

我们知道目前Ubuntu手机平台有些类似iPhone平台,是一个单任务的操作系统,虽然系统本身具有多任务的功能.如果当前的应用被推到后台的话,应用将会被自动挂起,而不会被系统所运行.在这个时候如果我们的应用需要等待一个消息,比如就想微信之类的信息,我们就要使用Ubuntu平台所提供的Push Notification机制来实现我们的类似多任务的东西.当通知被收到后,我们就可以直接点击接受到的通知,应用又会被重新运行到前台. 关于Push notification,在我们的开发者网站上,有一篇文章