Apple Notifiche push Provider in c#

Io sono completamente Nuovo per Apple Notifiche Push servizio. Sto cercando di implementare per le mie applicazioni. Ho cercato in google, come pure in stackoverflow, ma non soddisfatto. Sto cercando di implementare provider in c#. Ho provato MoonAPNs troppo.

Qui c’è qualcuno che può suggerirmi un buon tutorial passo passo su di esso che è molto semplice. Ho già ottenuto ios developer e apn, oltre ai certificati p12 chiave. Ho bisogno di aiuto allora.
Grazie in anticipo.

  • Ho un lavoro completo, esempio di utilizzo di PushSharp. Appena mi arriva al lavoro, io vi darò info.
  • il tuo aiuto sarà molto apprezzato.
  • Aggiunta di un esempio (abbastanza completa).
InformationsquelleAutor Lasang | 2013-01-11

 

3 Replies
  1. 19

    Qui è l’infrastruttura e il processo che sto utilizzando:

    Breve Panoramica:
    Io uso PushSharp per comunicare con il server APN. Ho un SQL Server backend DB installazione di gestire tutte le sottoscrizioni e le notifiche vengono inviate. Anche io ho un server virtuale (molti in realtà) che tutti abbiano la .p12 certs copiato a loro. Questi server hanno un processo che controlla la tabella per eventuali notifiche push che hanno bisogno di andare fuori e poi passare dataset lungo la PushSharp processo.

    Specifiche Dettagliate:
    Tabella 1 – APNS_Subscriptions

    CREATE TABLE [dbo].[APNS_Subscriptions](
        [id] [int] IDENTITY(1,1) NOT NULL,
        [DeviceToken] [varchar](250) NULL,
        [DeviceID] [varchar](250) NULL,
        [NetworkID] [varchar](250) NULL,
        [Application] [varchar](250) NULL,
        [AddedOn] [datetime] NULL,
        [Active] [bit] NULL,
        [Dev] [bit] NULL,
        [BadgeCount] [int] NOT NULL,
     CONSTRAINT [PK_APNSSubscriptions] PRIMARY KEY CLUSTERED 
    (
        [id] ASC
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON [PRIMARY]

    Tabella 2 – APNS_PushNotifications

    CREATE TABLE [dbo].[APNS_PushNotifications](
        [id] [int] IDENTITY(1,1) NOT NULL,
        [DeviceToken] [varchar](250) NULL,
        [AlertMessage] [varchar](250) NULL,
        [BadgeNumber] [int] NULL,
        [SoundFile] [varchar](250) NULL,
        [ApplicationName] [varchar](250) NULL,
        [AddedOn] [datetime] NULL,
        [AddedBy] [varchar](250) NULL,
        [ProcessedOn] [datetime] NULL,
        [ViewedOnDeviceDateTime] [datetime] NULL,
     CONSTRAINT [PK_APNS_PushNotifications] PRIMARY KEY CLUSTERED 
    (
        [id] ASC
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON [PRIMARY]

    Aggiungere le sottoscrizioni tramite questo SP (questo è chiamato tramite un webservice via ogni app per iPhone che implementa APN:

    [ins_APNS_Sub]
        @MyDeviceID VARCHAR(250) ,
        @MyDeviceToken VARCHAR(250) ,
        @MyApplicationName VARCHAR(250)
    AS 
        DECLARE @Count AS INT
    
        SET @Count = ( SELECT   COUNT(id)
                       FROM     dbo.APNS_Subscriptions
                       WHERE    DeviceID = @MyDeviceID
                                AND DeviceToken = @MyDeviceToken
                                AND [Application] = @MyApplicationName
                     )
    
        IF @Count = 0 
            BEGIN
                DECLARE @NetworkID AS VARCHAR(250)
                SET @NetworkID = ( SELECT TOP 1
                                            networkid
                                   FROM     dbo.AuthenticatedDevices
                                   WHERE    deviceid = @MyDeviceID
                                            AND COALESCE(banned, 0) = 0
                                   ORDER BY lastupdatedon DESC
                                 )
    
                IF @NetworkID IS NOT NULL 
                    BEGIN
    
                        INSERT  INTO dbo.APNS_Subscriptions
                                ( DeviceToken ,
                                  DeviceID ,
                                  NetworkID ,
                                  [Application] ,
                                  AddedOn ,
                                  Active
                                )
                        VALUES  ( @MyDeviceToken , -- DeviceToken - varchar(250)
                                  @MyDeviceID , -- DeviceID - varchar(250)
                                  @NetworkID , -- NetworkID - varchar(250)
                                  @MyApplicationName , -- Application - varchar(250)
                                  CURRENT_TIMESTAMP , -- AddedOn - datetime
                                  1  -- Active - bit
                                )
                    END
            END

    Le Notifiche Push vengono aggiunti tramite questo SP:

    [ins_APNS_PushNote]
        @MyNetworkID VARCHAR(250) ,  -- NetworkID of recipient or ALL to go to all recipients
        @MyApplicationName VARCHAR(250) ,  -- Application Name for the iOS app
        @APNSAlertMessage VARCHAR(225) , -- Alert Message (Required)
        @APNSSoundFile VARCHAR(250) = NULL ,
        @WhoRequested VARCHAR(250) -- Process Name that called this SP
    AS 
    
    
       -- Get the current badge count, make a temp table and increment the appropriate rows in the Sub table
        DECLARE @UpdateTable AS TABLE
            (
              DeviceToken VARCHAR(250) ,
              NetworkID VARCHAR(250) ,
              ApplicationName VARCHAR(250) ,
              BadgeCount INT
            )
    
        IF @MyNetworkID = 'ALL' 
            BEGIN
    
                INSERT  INTO @UpdateTable
                        ( DeviceToken ,
                          NetworkID ,
                          ApplicationName ,
                          BadgeCount
                        )
                        SELECT  DeviceToken ,
                                NetworkID ,
                                [Application] ,
                                BadgeCount
                        FROM    dbo.APNS_Subscriptions
                        WHERE   [Application] = @MyApplicationName
                                AND COALESCE(Dev, 0) = 0
    
                UPDATE  @UpdateTable
                SET     BadgeCount = BadgeCount + 1
    
                UPDATE  sub
                SET     sub.BadgeCount = temp.BadgeCount
                FROM    dbo.APNS_Subscriptions sub
                        INNER JOIN @UpdateTable temp ON temp.DeviceToken = sub.DeviceToken
                                                        AND temp.NetworkID = sub.NetworkID
                                                        AND temp.ApplicationName = sub.[Application]
    
                INSERT  INTO dbo.APNS_PushNotifications
                        ( DeviceToken ,
                          AlertMessage ,
                          BadgeNumber ,
                          SoundFile ,
                          ApplicationName ,
                          AddedOn ,
                          AddedBy
    
                        )
                        SELECT  sub.DeviceToken ,
                                @APNSAlertMessage ,
                                temp.BadgeCount ,
                                @APNSSoundFile ,
                                @MyApplicationName ,
                                CURRENT_TIMESTAMP ,
                                @WhoRequested
                        FROM    dbo.APNS_Subscriptions sub
                                INNER JOIN dbo.AuthenticatedDevices ad ON ad.deviceid = sub.DeviceID
                                INNER JOIN @UpdateTable temp ON temp.DeviceToken = sub.DeviceToken
                                                                AND temp.ApplicationName = sub.[Application]
                        WHERE   COALESCE(ad.banned, 0) = 0
                                AND sub.[Application] = @MyApplicationName
                                  --  AND ad.networkid = @MyNetworkID
                                AND COALESCE(sub.Dev, 0) = 0
            END    
        ELSE 
            BEGIN
    
                DECLARE @Count AS INT = ( SELECT    COUNT(id)
                                          FROM      dbo.APNS_Subscriptions
                                          WHERE     NetworkID = @MyNetworkID
                                                    AND Active = 1
                                                    AND [Application] = @MyApplicationName
                                        )
    
    
                IF @Count = 0 
                    BEGIN
                        RETURN
                    END     
    
                INSERT  INTO @UpdateTable
                        ( DeviceToken ,
                          NetworkID ,
                          ApplicationName ,
                          BadgeCount
                        )
                        SELECT  DeviceToken ,
                                NetworkID ,
                                [Application] ,
                                BadgeCount
                        FROM    dbo.APNS_Subscriptions
                        WHERE   [Application] = @MyApplicationName
                                AND COALESCE(Dev, 0) = 0
                                AND NetworkID = @MyNetworkID
    
                UPDATE  @UpdateTable
                SET     BadgeCount = BadgeCount + 1
    
                UPDATE  sub
                SET     sub.BadgeCount = temp.BadgeCount
                FROM    dbo.APNS_Subscriptions sub
                        INNER JOIN @UpdateTable temp ON temp.DeviceToken = sub.DeviceToken
                                                        AND temp.NetworkID = sub.NetworkID
                                                        AND temp.ApplicationName = sub.[Application]
    
                INSERT  INTO dbo.APNS_PushNotifications
                        ( DeviceToken ,
                          AlertMessage ,
                          BadgeNumber ,
                          SoundFile ,
                          ApplicationName ,
                          AddedOn ,
                          AddedBy
    
                        )
                        SELECT  sub.DeviceToken ,
                                @APNSAlertMessage ,
                                temp.BadgeCount ,
                                @APNSSoundFile ,
                                @MyApplicationName ,
                                CURRENT_TIMESTAMP ,
                                @WhoRequested
                        FROM    dbo.APNS_Subscriptions sub
                                INNER JOIN dbo.AuthenticatedDevices ad ON ad.deviceid = sub.DeviceID
                                INNER JOIN @UpdateTable temp ON temp.DeviceToken = sub.DeviceToken
                                                                AND temp.ApplicationName = sub.[Application]
                        WHERE   COALESCE(ad.banned, 0) = 0
                                AND sub.[Application] = @MyApplicationName
                                AND sub.networkid = @MyNetworkID
                                AND COALESCE(sub.Dev, 0) = 0
                                AND COALESCE(sub.Active, 0) = 1
    
            END   

    Questo è chiamato da molti luoghi diversi in diversi DB in questo modo:
    ESEGUIRE [ins_APNS_PushNote]
    @NetworkID
    ,@iOSApplicationName
    ,@AlertMessage
    ,@SoundFile
    ,@RequestedBy

    SP che recupera questi APN richieste per il server virtuale (PushSharp):

    [get_APNSToSend]
    AS 
        BEGIN
    
            DECLARE @CurrentTimestamp AS DATETIME = CURRENT_TIMESTAMP
    
            UPDATE dbo.APNS_PushNotifications
            SET ProcessedOn = CURRENT_TIMESTAMP
            WHERE ProcessedOn IS NULL
    
            SELECT  id ,
                    DeviceToken ,
                    AlertMessage ,
                    BadgeNumber ,
                    SoundFile ,
                    ai.APNSDistCertFile AS APNSCertFile
            FROM    dbo.APNS_PushNotifications apns
                    INNER JOIN dbo.ApplicationInfo ai ON ai.ApplicationName = apns.ApplicationName
            WHERE   ProcessedOn = @CurrentTimestamp
                    AND ai.APNSDistCertFile IS NOT NULL
    
    
        END 

    Ora per le modifiche che ho fatto al PushSharp app. In realtà solo riduce a due metodi:
    static void Main(string[] args)
    {
    checkForPushRequest();
    }

        static void checkForPushRequest()
        {
            string YourConnString = "YourConnectionStringToTheDBGoesHere";
    
                Stored_Procedure SP = new Stored_Procedure {
                Name = "get_APNSToSend",
                Parameters = new List<SqlParameter>()
            };
    
            try {
                System.Data.DataTable dt = DatabaseOperations.Execute_Database_Command(YourConnString, SP, true);
    
                if ((dt != null) && !(dt.Rows.Count < 1)) {
                    foreach (System.Data.DataRow dRow in dt.Rows) {
                        string deviceToken = Convert.ToString(dRow[1]);
                        string alertMessage = Convert.ToString(dRow[2]);
                        int badgeNumber =  Convert.ToInt16(dRow[3]);
                        string soundFile = Convert.ToString(dRow[4]);
                        string apnsCertFileToUse = Convert.ToString(dRow[5]);
                        sendPush(deviceToken, alertMessage, soundFile, badgeNumber, apnsCertFileToUse);
                    }
                }
            } catch (Exception ex) {
                //Handle your exception
            }
        }
    
        static void sendPush(string DeviceToken, string AlertMessage, string SoundFile, int BadgeNumber, string apnsCertFileToUse)
        {
            //Create our service    
            PushService push = new PushService();
    
            //Wire up the events
            push.Events.OnDeviceSubscriptionExpired += new PushSharp.Common.ChannelEvents.DeviceSubscriptionExpired(Events_OnDeviceSubscriptionExpired);
            //push.Events.OnDeviceSubscriptionIdChanged += new PushSharp.Common.ChannelEvents.DeviceSubscriptionIdChanged(Events_OnDeviceSubscriptionIdChanged);
            push.Events.OnChannelException += new PushSharp.Common.ChannelEvents.ChannelExceptionDelegate(Events_OnChannelException);
            push.Events.OnNotificationSendFailure += new PushSharp.Common.ChannelEvents.NotificationSendFailureDelegate(Events_OnNotificationSendFailure);
            push.Events.OnNotificationSent += new PushSharp.Common.ChannelEvents.NotificationSentDelegate(Events_OnNotificationSent);
    
            //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!  
            // This comes from the ApplicationInfo table.  Each app that supports APNS has it's own certfile name in the column
            string certFileToUse = "C:\\APNS_Certs\\" + apnsCertFileToUse;
    
            var appleCert = File.ReadAllBytes(certFileToUse);
    
            //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 'true')
            push.StartApplePushService(new ApplePushChannelSettings(false, appleCert, "P12PasswordHere"));
    
            //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(NotificationFactory.Apple()
                .ForDeviceToken(DeviceToken)
                .WithAlert(AlertMessage)
                .WithSound(SoundFile)
                .WithBadge(BadgeNumber));
    
            //Console.WriteLine("Waiting for Queue to Finish...");
    
            //Stop and wait for the queues to drains
            push.StopAllServices(true);
    
           //Console.WriteLine("Queue Finished, press return to exit...");         
        }

    Ho aggiunto un progetto di Console per il PushSharp soluzione e distribuito la Console al server APN. Questa applicazione console è attivato in base alle attività pianificata per l’esecuzione di ogni minuto.

    Se avete altre domande, fammi sapere. Ho utilizzato questo processo per l’ultimo dell’anno in un ambiente aziendale, e non hanno avuto problemi. Funziona perfettamente.

    • grazie per la condivisione di codice. Sto lavorando per questo e vi farò sapere se ho qualche problema. MOLTE GRAZIE
    • hai fatto un OTTIMA!!!!! lavoro. Grazie per la condivisione. Ho bisogno del vostro aiuto per la mia applicazione Adobe AIR. Ecco le mie domande: [1] la Mia applicazione gira su Android e ios sia. Fa il tuo lavoro la soluzione per me? Per comunicare l’ARIA e C# siamo in grado di utilizzare il webservice o WCF. [2] Che tipo di server virtuali che hai usato? Quali sono i ruoli di esso? [3] Quali sono i requisiti del server per l’installazione di PushSharp sul server. (come hosting Windows con MS SQL Server e….) In attesa di vostra risposta…. -Kapil
    • Wilson ciao, potresti condividere il AuthenticatedDevices tabella e, inoltre, ciò che è networkID? im supponendo thats un po ‘ come i canali?
    • che versione di PushSharp stai usando?
  2. 0

    Creare un APN push di notifica utilizzando in C# pagina web.Prima di creare un’applicazione web e iniziare un web form.

    web Form in fase di progettazione

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="iosp12.aspx.cs" Inherits="p12ios.iosp12" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
         <table class="auto-style1">
                <tr>
                    <td class="auto-style2">Device token</td>
                    <td>
                        <asp:TextBox ID="txtDeviceToken" runat="server"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td class="auto-style3">message</td>
                    <td class="auto-style4">
                        <asp:TextBox ID="txtMessage" runat="server" Height="44px"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td class="auto-style2">&nbsp;</td>
                    <td>
                        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" Width="142px" />
                    </td>
                </tr>
                <tr>
                    <td class="auto-style2">&nbsp;</td>
                    <td>
                        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
                    </td>
                </tr>
                <tr>
                    <td class="auto-style2">&nbsp;</td>
                    <td>&nbsp;</td>
                </tr>
            </table>
        </div>
        </form>
    </body>
    </html>

    Codice fase

    using System;
    using System.Web;
    using Newtonsoft.Json.Linq;
    using PushSharp.Apple;
    using System.Collections.Generic;
    
    namespace p12ios
    {
        public partial class iosp12 : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
    
            }
    
            protected void Button1_Click(object sender, EventArgs e)
            {
                SendPushNotification(txtDeviceToken.Text, txtMessage.Text);
            }
    
            private void SendPushNotification(string deviceToken, string message)
            {
                try
                {
    
                    //Get Certificate
                    var appleCert =   System.IO.File.ReadAllBytes(Server.MapPath("~/IOS/"p12 certificate""));
    
                    //Configuration (NOTE: .pfx can also be used here)
                    var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Sandbox, appleCert, "p12 Password");
    
                    //Create a new broker
                    var apnsBroker = new ApnsServiceBroker(config);
    
                    //Wire up events
                    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;
                                string desc = $"Apple Notification Failed: ID={apnsNotification.Identifier}, Code={statusCode}";
                                Console.WriteLine(desc);
                                Label1.Text = desc;
                            }
                            else
                            {
                                string desc = $"Apple Notification Failed for some unknown reason : {ex.InnerException}";
                                //Inner exception might hold more useful information like an ApnsConnectionException           
                                Console.WriteLine(desc);
                                Label1.Text = desc;
                            }
    
                            //Mark it as handled
                            return true;
                        });
                    };
    
                    apnsBroker.OnNotificationSucceeded += (notification) =>
                    {
                        Label1.Text = "Apple Notification Sent successfully!";
                    };
    
    
    
    
                    var fbs = new FeedbackService(config);
                    fbs.FeedbackReceived += (string devicToken, DateTime timestamp) =>
                    {
                        //Remove the deviceToken from your database
                        //timestamp is the time the token was reported as expired
                    };
    
                    //Start Proccess 
                    apnsBroker.Start();
    
                    var payload = new Dictionary<string, object>();
                    var aps = new Dictionary<string, object>();
                    aps.Add("alert", "This is a sample notification!");
                    aps.Add("badge", 1);
                    aps.Add("sound", "chime.aiff");
                    payload.Add("aps", aps);
    
                    payload.Add("confId", "20");
                    payload.Add("pageFormat", "Webs");
                    payload.Add("pageTitle", "Evalu");
                    payload.Add("webviewURL", "https:/UploadedImages/MobileApp/icons/Datalist-Defg");
                    payload.Add("notificationBlastID", "");
                    payload.Add("pushtype", "");
    
                    payload.Add("content-available", );
    
    
                    var jsonx = Newtonsoft.Json.JsonConvert.SerializeObject(payload);
    
                    if (deviceToken != "")
                    {
                        apnsBroker.QueueNotification(new ApnsNotification
                        {
                            DeviceToken = deviceToken,
                            Payload = JObject.Parse(Newtonsoft.Json.JsonConvert.SerializeObject(payload))
                        });
                    }
    
                    apnsBroker.Stop();
    
                }
                catch (Exception)
                {
    
                    throw;
                }
            }
        }
    
    }

    Payload ci scrivi il tuo JSON .Per installare spingere sharp. aprire il pacchetto nuget e aprire la console di gestione pacchetti. scrivere in console Install-Package PushSharp -Version 4.0.10 .Per utilizzare solo la chiave privata del certificato p12 e password.

Lascia un commento