PushSharp分离关注点

时间:2016-03-17 00:52:08

标签: c# pushsharp

我目前正在开发一个C#Web应用程序,并且我试图使用PushSharp软件包来获取推送通知。我的所有代码都在我的项目中的Global.asax文件中推送通知,但我一直收到错误:

using BYC.Models;
using BYC.Models.Enums;
using Newtonsoft.Json.Linq;
using PushSharp.Apple;
using PushSharp.Google;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace BYC
{
    public class WebApiApplication : System.Web.HttpApplication
    {

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
        protected void Application_End()
        {
            PushBrokerSingleton pbs = new PushBrokerSingleton();
            pbs.SendQueuedNotifications();
        }
    }

    public sealed class PushBrokerSingleton
    {
        private static ApnsServiceBroker Apns { get; set; }
        private static GcmServiceBroker Gcm { get; set; }
        private static bool ApnsStarted = false;
        private static bool GcmStarted = false;
        private static object AppleSyncVar = new object();
        private static object GcmSyncVar = new object();

        private static readonly log4net.ILog log = log4net.LogManager.GetLogger
(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public PushBrokerSingleton()
        {
            if (Apns == null)
        {
            string thumbprint = (AppSettings.Instance["APNS:Thumbprint"]);
            X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);

            ApnsConfiguration.ApnsServerEnvironment production = Convert.ToBoolean(AppSettings.Instance["APNS:Production"]) ?
                ApnsConfiguration.ApnsServerEnvironment.Production : ApnsConfiguration.ApnsServerEnvironment.Sandbox;

            X509Certificate2 appleCert = store.Certificates
              .Cast<X509Certificate2>()
              .SingleOrDefault(c => string.Equals(c.Thumbprint, thumbprint, StringComparison.OrdinalIgnoreCase));


            ApnsConfiguration apnsConfig = new ApnsConfiguration(production, appleCert);
            Apns = new ApnsServiceBroker(apnsConfig);
            Apns.OnNotificationFailed += (notification, aggregateEx) => {

                aggregateEx.Handle(ex => {

                    // See what kind of exception it was to further diagnose
                    if (ex is ApnsNotificationException)
                    {
                        var notificationException = ex as ApnsNotificationException;

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

                        log.Error($"Notification Failed: ID={apnsNotification.Identifier}, Code={statusCode}");

                    }
                    else {
                        // Inner exception might hold more useful information like an ApnsConnectionException           
                        log.Error($"Notification Failed for some (Unknown Reason) : {ex.InnerException}");
                    }

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

            Apns.OnNotificationSucceeded += (notification) => {
                log.Info("Notification Successfully Sent to: " + notification.DeviceToken);
            };
        }
        if(Gcm == null)
        {
            GcmConfiguration gcmConfig = new GcmConfiguration(AppSettings.Instance["GCM:Token"]);
            Gcm = new GcmServiceBroker(gcmConfig);
        }
    }

    public bool QueueNotification(Notification notification, Device device)
    {
        if (!ApnsStarted)
        {
            ApnsStarted = true;
            lock (AppleSyncVar)
            {
                Apns.Start();
            }
        }
        if(!GcmStarted)
        {
            GcmStarted = true;
            lock (GcmSyncVar)
            {
                Gcm.Start();
            }
        }
        switch (device.PlatformType)
        {
            case PlatformType.iOS:
                return QueueApplePushNotification(notification, device.PushRegistrationToken);
            case PlatformType.Android:
                return QueueAndroidPushNotification(notification, device.PushRegistrationToken);
            default: return false;
        }
    }

    private bool QueueApplePushNotification(Notification notification, string pushNotificationToken)
    {
        string appleJsonFormat = "{\"aps\": {\"alert\":" + '"' + notification.Subject + '"' + ",\"sound\": \"default\", \"badge\": " + notification.BadgeNumber + "}}";
        lock (AppleSyncVar)
        {
            Apns.QueueNotification(new ApnsNotification()
            {
                DeviceToken = pushNotificationToken,
                Payload = JObject.Parse(appleJsonFormat)
            });
        }
        return true;
    }

    private bool QueueAndroidPushNotification(Notification notification, string pushNotificationToken)
    {
        string message = "{\"alert\":\"" + notification.Subject + "\",\"badge\":" + notification.BadgeNumber + "\"}";
        lock (GcmSyncVar)
        {
            Gcm.QueueNotification(new GcmNotification()
            {
                RegistrationIds = new List<string>
                         {
                             pushNotificationToken
                         },
                Data = JObject.Parse(message),
                Notification = JObject.Parse(message)
            });
        }
        return true;
    }

    public void SendQueuedNotifications()
    {
        if(Apns != null)
        {
            if (ApnsStarted)
            {
                lock(AppleSyncVar){
                    Apns.Stop();
                    log.Info("Sent Apns Notifications");
                    ApnsStarted = false;
                }
            }
        }
        if(Gcm != null)
        {
            if (GcmStarted)
            {
                lock (GcmSyncVar)
                {
                    Gcm.Stop();
                    log.Info("Sent Gcm Notifications");
                    GcmStarted = false;
                }
            }
        }
    }
}

这是我的Global.asax文件:

var mod = angular.module('app');

mod.directive('decnumber', function () {
    return {
        require: 'ngModel',
        link: function (scope, element, attrs, modelCtrl) {
            var decnumber = function (inputValue) {

                if (inputValue == undefined) inputValue = "";
                var formattedVal = inputValue.replace(/[^0-9]/g, "").replace(/^0+/, "");

                if (formattedVal.length === 0) {
                    formattedVal = '0.00' + formattedVal;
                } else if (formattedVal.length === 1) {
                    formattedVal = '0.0' + formattedVal;
                } else if (formattedVal.length === 2) {
                    formattedVal = '0.' + formattedVal;
                } else {
                    formattedVal = formattedVal.slice(0, -2) + '.' + formattedVal.slice(-2);
                }

                if (formattedVal !== inputValue) {
                    modelCtrl.$setViewValue(formattedVal);
                    modelCtrl.$render();
                }
                return formattedVal;
            }
            modelCtrl.$parsers.unshift(decnumber);
            decnumber(scope[attrs.ngModel]);
        }
    };
});

}

1 个答案:

答案 0 :(得分:2)

当您尝试重用已调用ApnsServiceBroker的服务代理实例(例如:Stop())时会发生这种情况。

我猜你的Application_End在某个时刻被调用,Application_Start再次被调用,但是因为PushBrokerSingleton.Apns不是空的(它是一个静态字段所以它必须生活在虽然应用程序已停止/启动,但它永远不会被重新创建。

PushSharp很难与ASP.NET模式很好地协作,某种服务守护进程会更好。

主要问题是您的应用可能会被回收或在您不期望的时候结束。同一应用中的无关请求可能会导致您的流程失效,或者您的AppDomain可能会被拆除。如果发生这种情况并且代理的Stop()调用无法成功结束,则某些排队的消息可能会丢失。这里有一篇关于一些警告的好文章:http://haacked.com/archive/2011/10/16/the-dangers-of-implementing-recurring-background-tasks-in-asp-net.aspx/在实践中,这可能不是什么大问题,你当然可以减轻它的一部分,但要记住它。

说了这么多,我认为一个简单的解决方法是在PushBrokerSingleton.Apns中创建PushBrokerSingleton.GcmApplication_Start的新实例。这可能会导致其他问题因此我不确定它是否是正确的修复程序,但是它可以解决在Stop()之后代理不应该重用的问题调用。

我还要考虑添加一些方法来'重置'集合。我不确定在.Stop()结束后自动执行此操作是个好主意,但我可能会考虑添加.Reset()或类似的方法来实现此目的。无论如何,现在完全可以接受创建新的代理实例。