Пример #1
0
		public static GcmNotification ForSingleRegistrationId(GcmNotification msg, string registrationId)
		{
			var result = new GcmNotification();
			result.Tag = msg.Tag;
			result.RegistrationIds.Add(registrationId);
			result.CollapseKey = msg.CollapseKey;
			result.JsonData = msg.JsonData;
			result.DelayWhileIdle = msg.DelayWhileIdle;
			return result;
		}
Пример #2
0
		public static GcmNotification ForSingleResult(GcmMessageTransportResponse response, int resultIndex)
		{
			var result = new GcmNotification();
			result.Tag = response.Message.Tag;
			result.RegistrationIds.Add(response.Message.RegistrationIds[resultIndex]);
			result.CollapseKey = response.Message.CollapseKey;
			result.JsonData = response.Message.JsonData;
			result.DelayWhileIdle = response.Message.DelayWhileIdle;
			return result;
		}
Пример #3
0
        public static GcmNotification ForSingleResult(GcmMessageTransportResponse response, int resultIndex)
        {
            var result = new GcmNotification();

            result.Tag = response.Message.Tag;
            result.RegistrationIds.Add(response.Message.RegistrationIds[resultIndex]);
            result.CollapseKey    = response.Message.CollapseKey;
            result.JsonData       = response.Message.JsonData;
            result.DelayWhileIdle = response.Message.DelayWhileIdle;
            return(result);
        }
Пример #4
0
        public static GcmNotification ForSingleRegistrationId(GcmNotification msg, string registrationId)
        {
            var result = new GcmNotification();

            result.Tag = msg.Tag;
            result.RegistrationIds.Add(registrationId);
            result.CollapseKey    = msg.CollapseKey;
            result.JsonData       = msg.JsonData;
            result.DelayWhileIdle = msg.DelayWhileIdle;
            return(result);
        }
        private static void SendAndroidNotifications(string json)
        {
            PushSharpServer.Instance.Broker.RegisterService<GcmNotification>(new GcmPushService(new GcmPushChannelSettings("493035910025", "AIzaSyDDqTCHFCp0eoXIp5BXKhLi0YTG6Ez8aFQ", "com.rdnation.droid")));

            var n = new GcmNotification();
            n.CollapseKey = "NONE";
            n.JsonData = json;

            var not = SiteCache.GetMobileNotifications().Where(x => x.MobileTypeEnum == MobileTypeEnum.Android).ToList();
            for (int i = 0; i < not.Count; i++)
                PushSharpServer.Instance.Broker.QueueNotification(GcmNotification.ForSingleRegistrationId(n, not[i].NotificationId));
        }
Пример #6
0
        void transport_UnhandledException(GcmNotification notification, Exception exception)
        {
            //Raise individual failures for each registration id for the notification
            foreach (var r in notification.RegistrationIds)
            {
                this.Events.RaiseNotificationSendFailure(GcmNotification.ForSingleRegistrationId(notification, r),
                                                         exception);
            }

            this.Events.RaiseChannelException(exception, PlatformType.AndroidGcm, notification);

            Interlocked.Decrement(ref waitCounter);
        }
 public void Send(GcmNotification msg, string senderAuthToken, string senderID, string applicationID)
 {
     try
     {
         send(msg, senderAuthToken, senderID, applicationID);
     }
     catch (Exception ex)
     {
         if (UnhandledException != null)
             UnhandledException(msg, ex);
         else
             throw ex;
     }
 }
Пример #8
0
 public bool PushNotification(Device device, JSONNotification notification)
 {
     // Check if gcm looks is valid
     if (!String.IsNullOrEmpty(device.GCM) && !String.IsNullOrWhiteSpace(device.GCM)) {
         try {
             GcmNotification notif = new GcmNotification().ForDeviceRegistrationId(device.GCM).WithJson(JsonConvert.SerializeObject(notification));
             _push.QueueNotification(notif);
             return true;
         } catch (Exception e) {
             return false;
         }
     } else {
         return false;
     }
 }
        public GcmProvider CreateNotification(object data, params string[] registrationIds)
        {
            GcmNotification notification = new GcmNotification { NotificationKey = ApiKey };

            foreach (string id in registrationIds)
                notification.RegistrationIds.Add(id);

            notification.JsonData = JsonConvert.SerializeObject(data, new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            });

            this.Notification = notification;
            return this;
        }
Пример #10
0
        void transport_MessageResponseReceived(GcmMessageTransportResponse response)
        {
            int index = 0;

            //Loop through every result in the response
            // We will raise events for each individual result so that the consumer of the library
            // can deal with individual registrationid's for the notification
            foreach (var r in response.Results)
            {
                var singleResultNotification = GcmNotification.ForSingleResult(response, index);

                if (r.ResponseStatus == GcmMessageTransportResponseStatus.Ok)
                {
                    //It worked! Raise success
                    this.Events.RaiseNotificationSent(singleResultNotification);
                }
                else if (r.ResponseStatus == GcmMessageTransportResponseStatus.CanonicalRegistrationId)
                {
                    //Swap Registrations Id's
                    var newRegistrationId = r.CanonicalRegistrationId;

                    this.Events.RaiseDeviceSubscriptionIdChanged(PlatformType.AndroidGcm, singleResultNotification.RegistrationIds[0], newRegistrationId, singleResultNotification);
                }
                else if (r.ResponseStatus == GcmMessageTransportResponseStatus.Unavailable)
                {
                    this.QueueNotification(singleResultNotification);
                }
                else if (r.ResponseStatus == GcmMessageTransportResponseStatus.NotRegistered)
                {
                    //Raise failure and device expired
                    this.Events.RaiseDeviceSubscriptionExpired(PlatformType.AndroidGcm, singleResultNotification.RegistrationIds[0], singleResultNotification);
                }
                else
                {
                    //Raise failure, for unknown reason
                    this.Events.RaiseNotificationSendFailure(singleResultNotification, new GcmMessageTransportException(r.ResponseStatus.ToString(), response));
                }

                index++;

                //decrement pending results.
                Interlocked.Decrement(ref PendingNotificationsResult);
            }

            Interlocked.Decrement(ref waitCounter);
        }
Пример #11
0
 public void Send(GcmNotification msg, string senderAuthToken, string senderID, string applicationID)
 {
     try
     {
         send(msg, senderAuthToken, senderID, applicationID);
     }
     catch (Exception ex)
     {
         if (UnhandledException != null)
         {
             UnhandledException(msg, ex);
         }
         else
         {
             throw ex;
         }
     }
 }
        public void SendMessage(string message, List<PushDeviceInfo> devices)
        {
            if (!this.isStarted) this.Start();
            this.isStarted = true;

            var androidAppList = devices.Where(x => x.Platform.ToLower() == "android").ToList();
            if (androidAppList.Any())
            {
                var firstOrDefault = androidAppList.FirstOrDefault();
                if (firstOrDefault != null)
                {
                    var a = new GcmNotification().ForDeviceRegistrationId(firstOrDefault.DeviceToken)
                             .WithJson("{\"message\":\" " + message + "\"}");
                    //.WithJson("{\"message\":\" " + message + "\",\"badge\":0,\"msgcnt\":\" " + msgcnt + "\"}");
                    //a.TimeToLive = this._timeToLive;
                    this._pushBroker.QueueNotification(a, androidAppName);
                }
            }
        }
Пример #13
0
        void requestStreamCallback(IAsyncResult result)
        {
            var msg = new GcmNotification();

            try
            {
                var asyncParam = result.AsyncState as GcmAsyncParameters;
                msg = asyncParam.Message;

                if (asyncParam != null)
                {
                    var wrStream = asyncParam.WebRequest.EndGetRequestStream(result);

                    using (var webReqStream = new StreamWriter(wrStream))
                    {
                        var data = asyncParam.Message.GetJson();
                        webReqStream.Write(data);
                        webReqStream.Close();
                    }

                    try
                    {
                        asyncParam.WebRequest.BeginGetResponse(new AsyncCallback(responseCallback), asyncParam);
                    }
                    catch (WebException wex)
                    {
                        asyncParam.WebResponse = wex.Response as HttpWebResponse;
                        processResponseError(asyncParam);
                    }
                }
            }
            catch (Exception ex)
            {
                if (UnhandledException != null)
                {
                    UnhandledException(msg, ex);
                }
                else
                {
                    throw ex;
                }
            }
        }
        public bool Send(GoogleGcmApiNotificationPayLoad payLoad)
        {
            HookEvents(PushBroker);

            try
            {
                PushBroker.RegisterService<GcmNotification>(new GcmPushService(new GcmPushChannelSettings(_Settings.GoogleApiAccessKey)));

                var notification = new GcmNotification()
                                    .ForDeviceRegistrationId(payLoad.Token)
                                    .WithJson(payLoad.GetGoogleFormattedJson());
                
                PushBroker.QueueNotification(notification);
            }
            finally 
            {
                StopBroker(); 
            }

            return true;
        }
Пример #15
0
        void requestStreamCallback(IAsyncResult result)
        {
            var asyncParam = result.AsyncState as GcmAsyncParameters;

            try
            {
                if (asyncParam != null)
                {
                    var wrStream = asyncParam.WebRequest.EndGetRequestStream(result);

                    using (var webReqStream = new StreamWriter(wrStream))
                    {
                        var data = asyncParam.Message.GetJson();
                        webReqStream.Write(data);
                        webReqStream.Close();
                    }

                    try
                    {
                        asyncParam.WebRequest.BeginGetResponse(new AsyncCallback(responseCallback), asyncParam);
                    }
                    catch (WebException wex)
                    {
                        asyncParam.WebResponse = wex.Response as HttpWebResponse;
                        processResponseError(asyncParam);
                    }
                }
            }
            catch (Exception ex)
            {
                //Raise individual failures for each registration id for the notification
                foreach (var r in asyncParam.Message.RegistrationIds)
                {
                    asyncParam.Callback(this, new SendNotificationResult(GcmNotification.ForSingleRegistrationId(asyncParam.Message, r), false, ex));
                }

                Interlocked.Decrement(ref waitCounter);
            }
        }
Пример #16
0
        void processResponseOk(GcmAsyncParameters asyncParam)
        {
            var result = new GcmMessageTransportResponse()
            {
                ResponseCode = GcmMessageTransportResponseCode.Ok,
                Message      = asyncParam.Message
            };

            //Get the response body
            var json = new JObject();

            var str = string.Empty;

            try { str = (new StreamReader(asyncParam.WebResponse.GetResponseStream())).ReadToEnd(); }
            catch { }

            try { json = JObject.Parse(str); }
            catch { }

            result.NumberOfCanonicalIds = json.Value <long>("canonical_ids");
            result.NumberOfFailures     = json.Value <long>("failure");
            result.NumberOfSuccesses    = json.Value <long>("success");

            var jsonResults = json["results"] as JArray;

            if (jsonResults == null)
            {
                jsonResults = new JArray();
            }

            foreach (var r in jsonResults)
            {
                var msgResult = new GcmMessageResult();

                msgResult.MessageId = r.Value <string>("message_id");
                msgResult.CanonicalRegistrationId = r.Value <string>("registration_id");
                msgResult.ResponseStatus          = GcmMessageTransportResponseStatus.Ok;

                if (!string.IsNullOrEmpty(msgResult.CanonicalRegistrationId))
                {
                    msgResult.ResponseStatus = GcmMessageTransportResponseStatus.CanonicalRegistrationId;
                }
                else if (r["error"] != null)
                {
                    var err = r.Value <string>("error") ?? "";

                    switch (err.ToLower().Trim())
                    {
                    case "ok":
                        msgResult.ResponseStatus = GcmMessageTransportResponseStatus.Ok;
                        break;

                    case "missingregistration":
                        msgResult.ResponseStatus = GcmMessageTransportResponseStatus.MissingRegistrationId;
                        break;

                    case "unavailable":
                        msgResult.ResponseStatus = GcmMessageTransportResponseStatus.Unavailable;
                        break;

                    case "notregistered":
                        msgResult.ResponseStatus = GcmMessageTransportResponseStatus.NotRegistered;
                        break;

                    case "invalidregistration":
                        msgResult.ResponseStatus = GcmMessageTransportResponseStatus.InvalidRegistration;
                        break;

                    case "mismatchsenderid":
                        msgResult.ResponseStatus = GcmMessageTransportResponseStatus.MismatchSenderId;
                        break;

                    case "messagetoobig":
                        msgResult.ResponseStatus = GcmMessageTransportResponseStatus.MessageTooBig;
                        break;

                    case "invaliddatakey":
                        msgResult.ResponseStatus = GcmMessageTransportResponseStatus.InvalidDataKey;
                        break;

                    case "invalidttl":
                        msgResult.ResponseStatus = GcmMessageTransportResponseStatus.InvalidTtl;
                        break;

                    case "internalservererror":
                        msgResult.ResponseStatus = GcmMessageTransportResponseStatus.InternalServerError;
                        break;

                    default:
                        msgResult.ResponseStatus = GcmMessageTransportResponseStatus.Error;
                        break;
                    }
                }

                result.Results.Add(msgResult);
            }

            asyncParam.WebResponse.Close();

            int index = 0;

            var response = result;

            //Loop through every result in the response
            // We will raise events for each individual result so that the consumer of the library
            // can deal with individual registrationid's for the notification
            foreach (var r in response.Results)
            {
                var singleResultNotification = GcmNotification.ForSingleResult(response, index);

                if (r.ResponseStatus == GcmMessageTransportResponseStatus.Ok)
                {
                    //It worked! Raise success
                    asyncParam.Callback(this, new SendNotificationResult(singleResultNotification));
                }
                else if (r.ResponseStatus == GcmMessageTransportResponseStatus.CanonicalRegistrationId)
                {
                    //Swap Registrations Id's
                    var newRegistrationId = r.CanonicalRegistrationId;
                    var oldRegistrationId = string.Empty;

                    if (singleResultNotification.RegistrationIds != null && singleResultNotification.RegistrationIds.Count > 0)
                    {
                        oldRegistrationId = singleResultNotification.RegistrationIds[0];
                    }

                    asyncParam.Callback(this, new SendNotificationResult(singleResultNotification, false, new DeviceSubscriptonExpiredException())
                    {
                        OldSubscriptionId = oldRegistrationId, NewSubscriptionId = newRegistrationId, IsSubscriptionExpired = true
                    });
                }
                else if (r.ResponseStatus == GcmMessageTransportResponseStatus.Unavailable)
                {
                    asyncParam.Callback(this, new SendNotificationResult(singleResultNotification, true, new Exception("Unavailable Response Status")));
                }
                else if (r.ResponseStatus == GcmMessageTransportResponseStatus.NotRegistered)
                {
                    var oldRegistrationId = string.Empty;

                    if (singleResultNotification.RegistrationIds != null && singleResultNotification.RegistrationIds.Count > 0)
                    {
                        oldRegistrationId = singleResultNotification.RegistrationIds[0];
                    }

                    //Raise failure and device expired
                    asyncParam.Callback(this, new SendNotificationResult(singleResultNotification, false, new DeviceSubscriptonExpiredException())
                    {
                        OldSubscriptionId = oldRegistrationId, IsSubscriptionExpired = true, SubscriptionExpiryUtc = DateTime.UtcNow
                    });
                }
                else
                {
                    //Raise failure, for unknown reason
                    asyncParam.Callback(this, new SendNotificationResult(singleResultNotification, false, new GcmMessageTransportException(r.ResponseStatus.ToString(), response)));
                }

                index++;
            }

            Interlocked.Decrement(ref waitCounter);
        }
        void send(GcmNotification msg, string senderAuthToken, string senderID, string applicationID)
        {
            var result = new GcmMessageTransportResponse();
            result.Message = msg;

            var postData = msg.GetJson();

            var webReq = (HttpWebRequest)WebRequest.Create(GCM_SEND_URL);
            //webReq.ContentLength = postData.Length;
            webReq.Method = "POST";
            webReq.ContentType = "application/json";
            //webReq.ContentType = "application/x-www-form-urlencoded;charset=UTF-8   can be used for plaintext bodies
            webReq.UserAgent = "PushSharp (version: 1.0)";
            webReq.Headers.Add("Authorization: key=" + senderAuthToken);

            webReq.BeginGetRequestStream(new AsyncCallback(requestStreamCallback), new GcmAsyncParameters()
            {
                WebRequest = webReq,
                WebResponse = null,
                Message = msg,
                SenderAuthToken = senderAuthToken,
                SenderId = senderID,
                ApplicationId = applicationID
            });
        }
        void responseCallback(IAsyncResult result)
        {
            var msg = new GcmNotification();

            try
            {
                var asyncParam = result.AsyncState as GcmAsyncParameters;
                msg = asyncParam.Message;

                try
                {
                    asyncParam.WebResponse = asyncParam.WebRequest.EndGetResponse(result) as HttpWebResponse;
                    processResponseOk(asyncParam);
                }
                catch (WebException wex)
                {
                    asyncParam.WebResponse = wex.Response as HttpWebResponse;
                    processResponseError(asyncParam);
                }
            }
            catch (Exception ex)
            {
                if (UnhandledException != null)
                    UnhandledException(msg, ex);
                else
                    throw ex;
            }
        }
        void requestStreamCallback(IAsyncResult result)
        {
            var msg = new GcmNotification();

            try
            {
                var asyncParam = result.AsyncState as GcmAsyncParameters;
                msg = asyncParam.Message;

                if (asyncParam != null)
                {
                    var wrStream = asyncParam.WebRequest.EndGetRequestStream(result);

                    using (var webReqStream = new StreamWriter(wrStream))
                    {
                        var data = asyncParam.Message.GetJson();
                        webReqStream.Write(data);
                        webReqStream.Close();
                    }

                    try
                    {
                        asyncParam.WebRequest.BeginGetResponse(new AsyncCallback(responseCallback), asyncParam);
                    }
                    catch (WebException wex)
                    {
                        asyncParam.WebResponse = wex.Response as HttpWebResponse;
                        processResponseError(asyncParam);
                    }
                }
            }
            catch (Exception ex)
            {
                if (UnhandledException != null)
                    UnhandledException(msg, ex);
                else
                    throw ex;
            }
        }
Пример #20
0
 static void NotifyTargetChanged(LocationShare t)
 {
     var not = new GcmNotification ();
     not.RegistrationIds.AddRange (t.Trackers.Select (tr => tr.RegistrationId));
     not.JsonData = string.Format ("{event:\"TargetChanged\", trackedShareId:\"{0}\", latitude:\"{1}\", longitude:\"{2}\"}", t.PublicId, t.Latitude, t.Longitude);
     StringBuilder sb = new StringBuilder ();
     sb.Append ("{");
     sb.Append ("event:\"TargetChanged\", ");
     sb.Append ("trackedShareId:\"").Append (t.PublicId).Append ("\", ");
     sb.Append ("latitude:\"").Append (t.Latitude.ToString (CultureInfo.InvariantCulture)).Append ("\", ");
     sb.Append ("longitude:\"").Append (t.Longitude.ToString (CultureInfo.InvariantCulture)).Append ("\"");
     sb.Append ("}");
     not.JsonData = sb.ToString ();
     pushService.QueueNotification (not);
 }
        /// <summary>
        /// The main processor method used to process a single push notification, checks if the processing will be an immediate single push or regular thread looping model. 
        /// Looks up for a single (or more if you wish) entity in the databae which has not been processed. 
        /// Puts the fetched unprocessed push notification entity to processing over the Push Sharp API. 
        /// Finally saves the state of processing.
        /// </summary>
        /// <param name="databaseContext">The current database context to be used for processing to the database.</param>
        /// <param name="pushNotification">A single push notification entity to be processed and saved.</param>
        /// <param name="isDirectSinglePush">Decides wethere the processing will take place immediately for the sent notification or will the method lookup from the database for a first unprocessed push notification.</param>
        /// <returns>True if all OK, false if not.</returns>
        public bool ProcessNotification(PushSharpDatabaseContext dbContext, PushNotification pushNotification = null, bool isDirectSinglePush = false)
        {
            _databaseContext = dbContext;
            _isDirectSinglePush = isDirectSinglePush;

            if (_isDirectSinglePush)
                InitBroker();

            On(DisplayMessage, "Checking for unprocessed notifications...");
            PushNotification notificationEntity = pushNotification;

            try
            {
                if (notificationEntity != null)
                {
                    // save a new immediate unprocessed push notification
                    _databaseContext.PushNotification.Add(pushNotification);
                    _databaseContext.SaveChanges();

                    // reload the entity
                    notificationEntity = _databaseContext.PushNotification
                        .Where(x => x.ID == pushNotification.ID)
                        .Include(x => x.MobileDevice)
                        .Include(x => x.MobileDevice.Client)
                        .FirstOrDefault();
                }
                else // take one latest unprocessed notification, this can be changed to take any set size instead of one
                    notificationEntity = _databaseContext.PushNotification.FirstOrDefault(s =>
                        s.Status == (int)PushNotificationStatus.Unprocessed &&
                        s.CreatedAt <= DateTime.Now);
            }
            catch (Exception ex)
            {
                On(DisplayErrorMessage, "EX. ERROR: Check for unprocessed notifications: " + ex.Message);
                SimpleErrorLogger.LogError(ex);
            }

            // Process i.e. push the push notification via PushSharp... 
            if (notificationEntity != null)
            {
                bool messagePushed = true;

                On(DisplayStatusMessage, "Processing notification...");
                On(DisplayMessage, "ID " + notificationEntity.ID + " for " + notificationEntity.MobileDevice.Client.Username + " -> " + notificationEntity.Message);

                //---------------------------
                // ANDROID GCM NOTIFICATIONS
                //---------------------------
                if (notificationEntity.MobileDevice.SmartphonePlatform == "android")
                {
                    var gcmNotif = new GcmNotification() { Tag = notificationEntity.ID };
                    string msg = JsonConvert.SerializeObject(new { message = notificationEntity.Message });

                    gcmNotif.ForDeviceRegistrationId(notificationEntity.MobileDevice.PushNotificationsRegistrationID)
                            .WithJson(msg);

                    _broker.QueueNotification(gcmNotif);
                    UpdateNotificationQueued(notificationEntity);
                }
                ////-------------------------
                //// APPLE iOS NOTIFICATIONS
                ////-------------------------
                else if (notificationEntity.MobileDevice.SmartphonePlatform == "ios")
                {
                    var appleNotif = new AppleNotification() { Tag = notificationEntity.ID };
                    var msg = new AppleNotificationPayload(notificationEntity.Message);

                    appleNotif.ForDeviceToken(notificationEntity.MobileDevice.PushNotificationsRegistrationID)
                                .WithPayload(msg)
                                .WithSound("default");

                    _broker.QueueNotification(appleNotif);
                    UpdateNotificationQueued(notificationEntity);
                }
                //----------------------
                // WINDOWS NOTIFICATIONS
                //----------------------
                else if (notificationEntity.MobileDevice.SmartphonePlatform.Equals("wp") || notificationEntity.MobileDevice.SmartphonePlatform.Equals("wsa"))
                {
                    var wNotif = new WindowsToastNotification() { Tag = notificationEntity.ID };

                    wNotif.ForChannelUri(notificationEntity.MobileDevice.PushNotificationsRegistrationID)
                        .AsToastText02("PushSharp Notification", notificationEntity.Message);

                    _broker.QueueNotification(wNotif);
                    UpdateNotificationQueued(notificationEntity);
                }
                else
                {
                    On(DisplayErrorMessage, "ERROR: Unsupported device OS: " + notificationEntity.MobileDevice.SmartphonePlatform);

                    notificationEntity.Status = (int)PushNotificationStatus.Error;
                    notificationEntity.ModifiedAt = DateTime.Now;
                    notificationEntity.Description = "(Processor) Unsupported device OS: " + notificationEntity.MobileDevice.SmartphonePlatform;
                    SimpleErrorLogger.LogError(new Exception("EX. ERROR: " + notificationEntity.Description));
                    messagePushed = false;
                }

                try
                {
                    // Save changes to DB to keep the correct state of messages
                    _databaseContext.SaveChanges();

                    // bubble out the single push error, else return true to continue iteration
                    if (_isDirectSinglePush)
                        return messagePushed;

                    return true;
                }
                catch (Exception ex)
                {
                    On(DisplayErrorMessage, "EX. ERROR: Updating notification, DB save failed: " + ex.Message);
                    SimpleErrorLogger.LogError(ex);

                    // bubble out the single push error, else return true to continue iteration
                    if (_isDirectSinglePush)
                        return false;

                    return true;
                }
                finally
                {
                    if (_isDirectSinglePush)
                        KillBroker(_databaseContext);
                }
            }
            else
            {
                if (_isDirectSinglePush)
                    KillBroker(_databaseContext);

                // no messages were queued, take a nap...
                return false;
            }
        }
Пример #22
0
        private void EnqueueAndroidNotification(Device device, PushNotification notification)
        {
            var config = PushServiceConfiguration.GetSection();

            string json = string.Format(@"{{""message"":""{0}"",""msgcnt"":""{1}"",""regid"":""{2}""", notification.Message, device.Badge, device.RegistrationID);
            if (notification.Module != PushModule.Unknown && notification.Item != null)
            {
                var itemType = notification.Item.Type;
                var itemId = notification.Item.ID;

                if (notification.Item.Type == PushItemType.Subtask && notification.ParentItem != null)
                {
                    itemType = notification.ParentItem.Type;
                    itemId = notification.ParentItem.ID;
                }

                json += string.Format(@",""itemid"":""{0}"",""itemtype"":""{1}""", itemId, itemType.ToString().ToLower());
            }

            json += "}";

            var gcmNotification = new GcmNotification()
                .ForDeviceRegistrationId(device.Token)
                .WithJson(json);

            if (config.IsDebug || !config.Gcm.ElementInformation.IsPresent)
            {
                _log.DebugFormat("notification ({0}) prevented from sending to device {1}", gcmNotification, device.ID);
                return;
            }

            PushBrokerProvider.Instance.QueueNotification(gcmNotification);
        }
 public GcmProvider()
 {
     ApiKey = WebConfigurationManager.AppSettings["GcmApiKey"];
     this.Notification = new GcmNotification();
 }
Пример #24
0
 static void NotifyTrackerAdded(TrackerData t)
 {
     var not = new GcmNotification ();
     not.RegistrationIds.Add (t.UserRegistrationId);
     StringBuilder sb = new StringBuilder ();
     sb.Append ("{event:\"TrackerAdded\", shareId:\"").Append (t.SharePrivateId).Append ("\", trackerId:\"").Append (t.TrackerId).Append ("\"}");
     not.JsonData = sb.ToString ();
     LogService.Log ("Sending message: " + sb.ToString ());
     pushService.QueueNotification (not);
 }
Пример #25
0
        void transport_UnhandledException(GcmNotification notification, Exception exception)
        {
            //Raise individual failures for each registration id for the notification
            foreach (var r in notification.RegistrationIds)
            {
                this.Events.RaiseNotificationSendFailure(GcmNotification.ForSingleRegistrationId(notification, r),
                    exception);
            }

            this.Events.RaiseChannelException(exception, PlatformType.AndroidGcm, notification);

            Interlocked.Decrement(ref waitCounter);
        }
Пример #26
0
        void transport_UnhandledException(GcmNotification notification, Exception exception)
        {
            //Raise individual failures for each registration id for the notification
            foreach (var r in notification.RegistrationIds)
            {
                this.Events.RaiseNotificationSendFailure(GcmNotification.ForSingleRegistrationId(notification, r),
                    exception);
            }

            this.Events.RaiseChannelException(exception);
        }
Пример #27
0
		public void TestNotifications(bool shouldBatch, int toQueue, int expectSuccessful, int expectFailed, int[] indexesToFail = null, bool waitForScaling = false)
		{
			testPort++;

			int msgIdOn = 1000;

			int pushFailCount = 0;
			int pushSuccessCount = 0;

			int serverReceivedCount = 0;
			int serverReceivedFailCount = 0;
			int serverReceivedSuccessCount = 0;

			//var notification = new GcmNotification();

			var server = new TestServers.GcmTestServer();

			server.MessageResponseFilters.Add(new GcmMessageResponseFilter()
			{
				IsMatch = (request, s) => {
					return s.Equals("FAIL", StringComparison.InvariantCultureIgnoreCase);
				},
				Status = new GcmMessageResult() { 
					ResponseStatus = GcmMessageTransportResponseStatus.InvalidRegistration,
					MessageId = "1:" + msgIdOn++
				}
			});

			server.MessageResponseFilters.Add(new GcmMessageResponseFilter()
			                                  {
				IsMatch = (request, s) => {
					return s.Equals("NOTREGISTERED", StringComparison.InvariantCultureIgnoreCase);
				},
				Status = new GcmMessageResult() { 
					ResponseStatus = GcmMessageTransportResponseStatus.NotRegistered,
					MessageId = "1:" + msgIdOn++
				}
			});
			//var waitServerFinished = new ManualResetEvent(false);
			
			server.Start(testPort, response =>
						{
							serverReceivedCount += (int)response.NumberOfCanonicalIds;
							serverReceivedSuccessCount += (int) response.NumberOfSuccesses;
							serverReceivedFailCount += (int) response.NumberOfFailures;
						});

			

			var settings = new GcmPushChannelSettings("SENDERAUTHTOKEN");
			settings.OverrideUrl("http://*****:*****@"{""key"":""value1""}";

			if (shouldBatch)
			{
				var regIds = new List<string>();

				for (int i = 0; i < toQueue; i++)
					regIds.Add((indexesToFail != null && indexesToFail.Contains(i)) ? "FAIL" : "SUCCESS");

				var n = new GcmNotification();
				n.RegistrationIds.AddRange(regIds);
				n.WithJson(json);
				
				push.QueueNotification(n);
			}
			else
			{
				for (int i = 0; i < toQueue; i++)
					push.QueueNotification(new GcmNotification()
						.ForDeviceRegistrationId((indexesToFail != null && indexesToFail.Contains(i)) ? "FAIL" : "SUCCESS")
						.WithJson(json));
			}

			

			

            Console.WriteLine("Avg Queue Wait Time: " + push.AverageQueueWaitTime + " ms");
            Console.WriteLine("Avg Send Time: " + push.AverageSendTime + " ms");

            if (waitForScaling)
            {
               while (push.QueueLength > 0)
                   Thread.Sleep(500);

                Console.WriteLine("Sleeping 3 minutes for autoscaling...");
                Thread.Sleep(TimeSpan.FromMinutes(3));

                Console.WriteLine("Channel Count: " + push.ChannelCount);
                Assert.IsTrue(push.ChannelCount <= 1);
            }

            push.Stop();
			push.Dispose();

			server.Dispose();
			//waitServerFinished.WaitOne();

			Console.WriteLine("TEST-> DISPOSE.");

			Assert.AreEqual(toQueue, serverReceivedCount, "Server - Received Count");
			Assert.AreEqual(expectFailed, serverReceivedFailCount, "Server - Failed Count");
			Assert.AreEqual(expectSuccessful, serverReceivedSuccessCount, "Server - Success Count");

			Assert.AreEqual(expectFailed, pushFailCount, "Client - Failed Count");
			Assert.AreEqual(expectSuccessful, pushSuccessCount, "Client - Success Count");
		}
Пример #28
0
        public void TestNotifications(bool shouldBatch, int toQueue, int expectSuccessful, int expectFailed, int[] indexesToFail = null)
        {
            testPort++;

            int msgIdOn = 1000;

            int pushFailCount = 0;
            int pushSuccessCount = 0;

            int serverReceivedCount = 0;
            int serverReceivedFailCount = 0;
            int serverReceivedSuccessCount = 0;

            //var notification = new GcmNotification();

            var server = new TestServers.GcmTestServer();

            server.MessageResponseFilters.Add(new GcmMessageResponseFilter()
            {
                IsMatch = (request, s) => {
                    return s.Equals("FAIL", StringComparison.InvariantCultureIgnoreCase);
                },
                Status = new GcmMessageResult() {
                    ResponseStatus = GcmMessageTransportResponseStatus.InvalidRegistration,
                    MessageId = "1:" + msgIdOn++
                }
            });

            server.MessageResponseFilters.Add(new GcmMessageResponseFilter()
                                              {
                IsMatch = (request, s) => {
                    return s.Equals("NOTREGISTERED", StringComparison.InvariantCultureIgnoreCase);
                },
                Status = new GcmMessageResult() {
                    ResponseStatus = GcmMessageTransportResponseStatus.NotRegistered,
                    MessageId = "1:" + msgIdOn++
                }
            });
            //var waitServerFinished = new ManualResetEvent(false);

            server.Start(testPort, response =>
                        {
                            serverReceivedCount += (int)response.NumberOfCanonicalIds;
                            serverReceivedSuccessCount += (int) response.NumberOfSuccesses;
                            serverReceivedFailCount += (int) response.NumberOfFailures;
                        });

            var settings = new GcmPushChannelSettings("SENDERAUTHTOKEN");
            settings.OverrideUrl("http://*****:*****@"{""key"":""value1""}";

            if (shouldBatch)
            {
                var regIds = new List<string>();

                for (int i = 0; i < toQueue; i++)
                    regIds.Add((indexesToFail != null && indexesToFail.Contains(i)) ? "FAIL" : "SUCCESS");

                var n = new GcmNotification();
                n.RegistrationIds.AddRange(regIds);
                n.WithJson(json);

                push.QueueNotification(n);
            }
            else
            {
                for (int i = 0; i < toQueue; i++)
                    push.QueueNotification(new GcmNotification()
                        .ForDeviceRegistrationId((indexesToFail != null && indexesToFail.Contains(i)) ? "FAIL" : "SUCCESS")
                        .WithJson(json));
            }

            push.Stop();
            push.Dispose();

            server.Dispose();
            //waitServerFinished.WaitOne();

            Console.WriteLine("TEST-> DISPOSE.");

            Assert.AreEqual(toQueue, serverReceivedCount, "Server - Received Count");
            Assert.AreEqual(expectFailed, serverReceivedFailCount, "Server - Failed Count");
            Assert.AreEqual(expectSuccessful, serverReceivedSuccessCount, "Server - Success Count");

            Assert.AreEqual(expectFailed, pushFailCount, "Client - Failed Count");
            Assert.AreEqual(expectSuccessful, pushSuccessCount, "Client - Success Count");
        }
 public GCMNotificationMessage(GcmNotification notification)
 {
     Token = notification.RegistrationIds.Single();
     Json = notification.JsonData;
 }