Exemplo n.º 1
0
        internal static void InformUserOfFailure(string email
            , TeamFoundationRequestContext requestContext, PushNotification pushNotification
            , List<Validation> validationResults)
        {
            var buf = new StringBuilder();
            buf.AppendFormat("{0}'s {1} request was refused for the following reasons:"
                , requestContext.GetNameToDisplay()
                , requestContext.ServiceName
                );
            buf.AppendLine();
            buf.AppendLine();
            foreach (var res in validationResults.Where(res => res.Fails))
            {
                buf.Append(" - ");
                buf.AppendLine(res.ReasonMessage);
            }
            buf.AppendLine();

            buf.AppendLine("Additional information:");
            buf.Append(requestContext.GetSummary());
            buf.AppendLine();

            var message = new MailMessage();
            message.From = new MailAddress(PluginConfiguration.Instance.EmailSender);
            message.To.Add(new MailAddress(email));
            message.Subject = "Push refused";
            message.Body = buf.ToString();
            var smtp = new SmtpClient(PluginConfiguration.Instance.EmailSmtpServer);
            smtp.Send(message);
        }
Exemplo n.º 2
0
        internal static void LogRequest(TeamFoundationRequestContext requestContext, PushNotification pushNotification, TfsGitRepository repository)
        {
            if (!PluginConfiguration.Instance.HasLog)
                return;

            var lines = new List<string>();

            lines.Add(string.Format("Request from {0} for {1}"
                , requestContext.GetNameToDisplay()
                , requestContext.ServiceName
                ));
            lines.Add("Summary for " + requestContext.GetSummary());

            lines.Add(string.Format("{6} #{0} on {1} repo {2} at {3} by {5} ({4})"
                , pushNotification.PushId
                , pushNotification.TeamProjectUri
                , pushNotification.RepositoryName
                , pushNotification.PushTime
                , pushNotification.AuthenticatedUserName
                , pushNotification.Pusher
                , requestContext.Method.Name
                ));

            lines.Add("- Included Commits:");
            foreach (var commitHash in pushNotification.IncludedCommits)
            {
                var commit = repository.TryLookupObject(requestContext, commitHash) as TfsGitCommit;
                lines.Add(string.Format("   Commit {0}: {1} '{2}'"
                    , commit.ObjectId.DisplayHash()
                    , commit.GetCommitterName(requestContext)
                    , commit.GetComment(requestContext)
                    ));

                foreach (var parentCommit in commit.GetParents(requestContext))
                {
                    lines.Add(string.Format("      Parent {0}: {1} '{2}'"
                        , parentCommit.ObjectId.DisplayHash()
                        , parentCommit.GetCommitterName(requestContext)
                        , parentCommit.GetComment(requestContext)
                        ));
                }
            }

            lines.Add("- Ref Update Results:");
            foreach (var refUpdate in pushNotification.RefUpdateResults)
            {
                lines.Add(string.Format("   on {0} {1}..{2} is {3} (succeeded: {4}) rejecter '{5}' message '{6}'"
                    , refUpdate.Name
                    , refUpdate.NewObjectId.DisplayHash()
                    , refUpdate.OldObjectId.DisplayHash()
                    , refUpdate.Status
                    , refUpdate.Succeeded
                    , refUpdate.RejectedBy
                    , refUpdate.CustomMessage
                    ));
            }//for

            File.AppendAllLines(PluginConfiguration.Instance.LogFile, lines);
        }
Exemplo n.º 3
0
 public List<Validation> CheckRules(TeamFoundationRequestContext requestContext, PushNotification pushNotification, TfsGitRepository repository)
 {
     var res = new List<Validation>();
     foreach (var rule in this.Rules)
     {
         res.Add(rule.CheckRule(requestContext, pushNotification, repository));
     }//for
     return res;
 }
Exemplo n.º 4
0
        public override Validation CheckRule(TeamFoundationRequestContext requestContext, PushNotification pushNotification, TfsGitRepository repository)
        {
            var result = new Validation();

            // refuse any push
            result.Fails = true;
            result.ReasonCode = 99;
            result.ReasonMessage = string.Format(
                "Repository '{0}' is in read-only mode",
                pushNotification.RepositoryName);

            return result;
        }
        protected bool IsUserExempted(TeamFoundationRequestContext requestContext, PushNotification pushNotification)
        {
            string collectionUrl = requestContext.GetCollectionUri();
            // client API
            TfsTeamProjectCollection tfs = new TfsTeamProjectCollection(new Uri(collectionUrl));
            var identityManagement = tfs.GetService<IIdentityManagementService>();
            var requestIdentity = identityManagement.ReadIdentity(IdentitySearchFactor.AccountName, pushNotification.AuthenticatedUserName, MembershipQuery.Direct, ReadIdentityOptions.None);

            bool exempted = false;
            foreach (var groupName in this.Groups)
            {
                var groupIdentity = identityManagement.ReadIdentity(IdentitySearchFactor.AccountName, groupName, MembershipQuery.Direct, ReadIdentityOptions.None);
                exempted |= identityManagement.IsMember(groupIdentity.Descriptor, requestIdentity.Descriptor);
            }//for
            return exempted;
        }
Exemplo n.º 6
0
        public override Validation CheckRule(TeamFoundationRequestContext requestContext, PushNotification pushNotification, TfsGitRepository repository)
        {
            var result = new Validation();

            long totalSize = 0;
            foreach (var commitId in pushNotification.IncludedCommits)
            {
                TfsGitCommit gitCommit = repository.LookupObject(requestContext, commitId) as TfsGitCommit;
                if (gitCommit == null)
                    continue;

                long size = GetCommitSize(gitCommit, requestContext);
                totalSize += size;
            }//for

            // convert to MB
            totalSize = totalSize / (1024 * 1024);

            if (totalSize < this.Megabytes)
            {
                Logger.Log(string.Format(
                    "Push request is {0} MB, below the {1} MB limit."
                    , totalSize, this.Megabytes
                    , "Limit Size"));
            }
            else
            {
                if (IsUserExempted(requestContext, pushNotification))
                {
                    Logger.Log(string.Format(
                        "Push request is {0} MB, above or equal to the {1} MB limit, but user is exempted."
                        , totalSize, this.Megabytes
                        , "Limit Size"));
                }
                else
                {
                    result.Fails = true;
                    result.ReasonCode = 2;
                    result.ReasonMessage = string.Format(
                        "Push request is {0} MB, above or equal to the {1} MB limit: refused."
                        , totalSize, this.Megabytes);
                }
            }//if

            return result;
        }
        public override Validation CheckRule(TeamFoundationRequestContext requestContext, PushNotification pushNotification, TfsGitRepository repository)
        {
            var result = new Validation();

            foreach (var refUpdateResult in pushNotification.RefUpdateResults)
            {
                // new or deleted refs have id==0
                if (IsNullHash(refUpdateResult.OldObjectId)
                    || IsNullHash(refUpdateResult.NewObjectId))
                    continue;

                TfsGitCommit gitCommit = repository.LookupObject(requestContext, refUpdateResult.NewObjectId) as TfsGitCommit;
                if (gitCommit == null)
                    continue;

                string authorEmail = gitCommit.GetAuthorEmail(requestContext);
                if (!AuthorEmail.Any(pattern => Regex.IsMatch(authorEmail, pattern)))
                {
                    result.Fails = true;
                    result.ReasonCode = 2;
                    result.ReasonMessage = string.Format(
                        "Author email '{0}' on commit {1} is not admitted",
                        authorEmail,
                        gitCommit.ObjectId.DisplayHash());
                    break;
                }

                string committerEmail = gitCommit.GetCommitterEmail(requestContext);
                if (!CommitterEmail.Any(pattern => Regex.IsMatch(committerEmail, pattern)))
                {
                    result.Fails = true;
                    result.ReasonCode = 3;
                    result.ReasonMessage = string.Format(
                        "Committer email '{0}' on commit {1} is not admitted",
                        authorEmail,
                        gitCommit.ObjectId.DisplayHash());
                    break;
                }//if
            }//for changes

            return result;
        }
Exemplo n.º 8
0
        //comment
        //direct_v2_message
        //
        public static void HandleNotify(PushNotification push, IReadOnlyList <IInstaApi> apiList)
        {
            switch (push.CollapseKey)
            {
            case "direct_v2_message":
                GoDirect(push, apiList.GetUserName(push.IntendedRecipientUserId));
                return;

            case "like":
                GoLike(push, apiList.GetUserName(push.IntendedRecipientUserId));
                return;

            case "comment":     //comment_like
                GoLike(push, apiList.GetUserName(push.IntendedRecipientUserId));
                return;

            default:
                Helpers.NotificationHelper.ShowToast(push.Message, push.OptionalAvatarUrl, push.Title ?? "");
                return;
            }
        }
        public int BuyProduct(User user, Product product)
        {
            try
            {
                BuyTransaction buyTransaction = new BuyTransaction(user, product.Price);
                TrackTransaction(buyTransaction);
                Logger.WriteMessage(buyTransaction.ToString() + " Product Name & ID: " + product.Name + product.Id);
            }
            catch (InsufficientCreditsException e)
            {
                Logger.WriteMessage("ID:" + user.Id + " There were not enough credits on the user's account");
                return(1);
            }

            // Trigger event to notify user
            if (user.Money <= 2000)
            {
                PushNotification?.Invoke(this, new UserBalanceNotificationArgs(user.Money));
            }
            return(0);
        }
Exemplo n.º 10
0
 void Update()
 {
     if (Input.GetKeyUp(KeyCode.Escape))
     {
         if (PlatformHelper.IsChannelTW())
         {
             if (!UIManager.PopOpenedList())
             {
                 PushNotification.NotificationMessage2Clinet();
                 PushNotification.NotificationMessage2Server();
                 doSdk("showQuit", "");
             }
         }
         else
         {
             PushNotification.NotificationMessage2Clinet();
             PushNotification.NotificationMessage2Server();
             doSdk("showQuit", "");
         }
     }
 }
Exemplo n.º 11
0
        private static Notify GetNotifyType(NotifyType notifyType)
        {
            Notify rtnNotify;

            switch (notifyType)
            {
            case NotifyType.PushNotification:
                rtnNotify = new PushNotification();
                break;

            case NotifyType.VoiceCall:
                rtnNotify = new VoiceCall();
                break;

            default:
                rtnNotify = new SMS();
                break;
            }

            return(rtnNotify);
        }
        /// <summary>
        /// prepare and send message to firebase servers
        /// </summary>
        /// <param name="notification">user notification</param>
        private async Task SendMessageAsync(PushNotification notification, CancellationToken cancellation = default)
        {
            var message = new Message
            {
                Data  = notification.PushNotificationProperties.Payload,
                Token = notification.PushNotificationProperties.DeviceToken
            };

            try
            {
                await firebaseMessaging.SendAsync(message, cancellation);

                logger.LogInformation($"UserId, {notification.User.UserId}, had a notification sent.");
            }
            catch (Exception e)
            {
                logger.LogError($"User, {notification.User.UserId}, failed to send push notification. Exception details: {e.InnerException}.");
                throw new HttpRequestException(
                          $"There was an issue sending a request to firebase push notification services. exception: {e}. Exception Details: {e.InnerException}.");
            }
        }
Exemplo n.º 13
0
        public static void HandleNotify(PushNotification push, string user)
        {
            switch (push.CollapseKey)
            {
            case "direct_v2_message":
                GoDirect(push, user);
                return;

            case "like":
                GoLike(push, user);
                return;

            case "comment":     //comment_like
                GoLike(push, user);
                return;

            default:
                NotificationHelper.ShowToast(push.Message, push.OptionalAvatarUrl, push.Title ?? "");
                return;
            }
        }
Exemplo n.º 14
0
        public Boolean NotifyAddParticipantToEvent(Event evt, List <string> adddedParticipantGcms)
        {
            try
            {
                //PushNotification pn = GetMessage(evt, "EventUpdate");
                if (adddedParticipantGcms.Count == 0)
                {
                    return(true);
                }

                PushNotification pn2 = GetMessage(evt, "EventInvite");

                //Get all participants gcms and remove newly added user gcms.
                //As existing users will get ParticipantsAdded notification
                //New users will get EventInvite notification
                //List<string> registrationIds = new List<string>();
                //evt.UserList.ForEach(user =>
                //{
                //    if ( !user.UserId.ToString().ToLower().Equals(evt.InitiatorId.ToString().ToLower()) )
                //    {
                //        if(! adddedParticipantGcms.Contains(user.GCMClientId))
                //        registrationIds.Add(user.GCMClientId);
                //    }
                //});

                adddedParticipantGcms = validateGcmIds(adddedParticipantGcms);
                //Notify newly added users of event invitation
                new NotificationTaskManager(new NotificationContainer()
                {
                    RegistrationIds = adddedParticipantGcms, NotificationData = pn2
                }).Enqueue();

                //this.notifier.SendInvite(registrationIds, pn);
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Exemplo n.º 15
0
        public static void HandleNotify(PushNotification push, IReadOnlyList <IInstaApi> apiList)
        {
            push.IgAction += $"&currentUser={push.IntendedRecipientUserId}";
            push.IgAction += $"&sourceUserId={push.SourceUserId}";
            push.IgAction += $"&collapseKey={push.CollapseKey}";
            push.IgAction += $"&pushCategory={push.PushCategory}";

            if (push.PushCategory == "direct_v2_pending")
            {
                GoDirectPendingRequest(push);
            }
            else if (push.CollapseKey == "direct_v2_message")
            {
                GoDirect(push, apiList.GetUserName(push.IntendedRecipientUserId));
            }
            else if (push.CollapseKey == "private_user_follow_request")
            {
                GoPrivateFriendshipRequest(push);
            }
            else if (push.CollapseKey == "live_broadcast")
            {
                GoLiveBroadcast(push);
            }
            else if (push.CollapseKey == "post")
            {
                GoNewPost(push);
            }
            else if (push.CollapseKey == "comment")
            {
                GoComment(push);
            }
            else if (push.CollapseKey == "subscribed_igtv_post")
            {
                GoNewIgtv(push);
            }
            else
            {
                GoLike(push, apiList.GetUserName(push.IntendedRecipientUserId));
            }
        }
Exemplo n.º 16
0
        private void SendNotification(PushNotification notificationDetails)
        {
            var notificationManager = NotificationManager.FromContext(this);

            var channelId = Covi.Configuration.Constants.PushNotificationsConstants.NotificationChannelName;

            var notificationId      = new Random().Next();
            var largeIcon           = BitmapFactory.DecodeResource(Resources, Resource.Mipmap.icon);
            var notificationBuilder =
                new NotificationCompat.Builder(this, channelId)
                .SetSmallIcon(Resource.Drawable.notification_icon)
                .SetLargeIcon(largeIcon)
                .SetPriority(NotificationCompat.PriorityHigh)
                .SetContentIntent(BuildIntentToShowMainActivity())
                .SetAutoCancel(true);

            if (!string.IsNullOrEmpty(notificationDetails.Title))
            {
                notificationBuilder.SetContentTitle(notificationDetails.Title);
            }

            if (!string.IsNullOrEmpty(notificationDetails.SubTitle))
            {
                notificationBuilder.SetSubText(notificationDetails.SubTitle);
            }

            if (!string.IsNullOrEmpty(notificationDetails.Description))
            {
                notificationBuilder.SetContentText(notificationDetails.Description);
                notificationBuilder.SetStyle(new NotificationCompat.BigTextStyle().BigText(notificationDetails.Description));
            }

            if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
            {
                notificationBuilder.SetChannelId(Covi.Configuration.Constants.PushNotificationsConstants.NotificationChannelName);
            }

            notificationManager.Notify(notificationId, notificationBuilder.Build());
        }
Exemplo n.º 17
0
        public async Task <JsonResult> SaveImageAction([FromBody] ImageAction action)
        {
            var actionExist =
                _databaseConnection.ImageActions.Where(
                    n => n.AppUserId == action.AppUserId && n.ImageId == action.ImageId).ToList();

            if (actionExist.Count <= 0)
            {
                _databaseConnection.Add(action);
                _databaseConnection.SaveChanges();
                var image = _databaseConnection.Images.SingleOrDefault(n => n.ImageId == action.ImageId);
                if (image != null)
                {
                    var notification = new PushNotification
                    {
                        AppUserId        = action.OwnerId,
                        CreatedBy        = action.AppUserId,
                        LastModifiedBy   = action.AppUserId,
                        DateLastModified = DateTime.Now,
                        DateCreated      = DateTime.Now,
                        Category         = SystemNotificationCategory.Comment.ToString(),
                        Read             = false,
                        ControllerId     = image.ImageId,
                        ClientId         = 4
                    };

                    var singleOrDefault = new AppUserFactory()
                                          .GetAllUsers(new AppConfig().FetchUsersUrl).Result
                                          .SingleOrDefault(n => n.AppUserId == image.AppUserId);
                    if (singleOrDefault != null)
                    {
                        notification.Message = singleOrDefault.Name +
                                               " Rated your Image";
                    }
                    await new AppUserFactory().SavePushNotification(new AppConfig().SavePushNotifications, notification);
                }
            }
            return(Json(action));
        }
Exemplo n.º 18
0
        public static void Main(string[] args)
        {
            var connection = new NotificationConnection(true, "certificate.pfx", "lalala");
            var client     = new PushNotification(connection);

            var notification = new NotificationPayload("<334b1ddf c30c4582 c497c058 c0d94ccf ad6409b2 7fa1ffbf 6f372427 7ba33e54>");

            notification.Badge = 0;
            notification.Alert = new Alert()
            {
                Body = "hello"
            };
            client.SendAsync(new[] { notification, notification, notification }).Wait();

            var feedbackConnection = new FeedbackConnection(true, "certificate.pfx", "lalala");
            var feedbackReader     = new FeedbackReader(feedbackConnection);


            var feedback = feedbackReader.GetFeedBackAsync().Result;

            System.Console.ReadLine();
        }
Exemplo n.º 19
0
        public async Task <IActionResult> SendPush(PushNotification notification)
        {
            string userEmail = User.FindFirst("email")?.Value ?? "NoUser";

            if (userEmail.ToUpper() != _adminEmail.ToUpper())
            {
                return(RedirectToAction("Index", "Home"));
            }

            if (notification.UserId.Contains('@'))
            {
                UserInfo userinfo = await _progenyHttpClient.GetUserInfo(notification.UserId);

                notification.UserId = userinfo.UserId;
            }

            await _pushMessageSender.SendMessage(notification.UserId, notification.Title, notification.Message,
                                                 notification.Link, "kinaunapush");

            notification.Title = "Message Sent";
            return(View(notification));
        }
Exemplo n.º 20
0
        public virtual ActionResult Save(EditPushNotificationModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    e = GetEvent(model.EventId);

                    if (model.Id == Guid.Empty)
                    {
                        pn = e.AddPushNotification((model.SendImmediately) ? e.NowLocal : model.SendDate.FullDate,
                                                   model.Message,
                                                   model.PlaySound);
                    }
                    else
                    {
                        pn = e.PushNotifications.Where(x => x.Id == model.Id).First();
                        if (pn.Sent)
                        {
                            throw new Exception("Can't edit Push Notifications already sent");
                        }

                        pn.SendDate  = (model.SendImmediately) ? e.NowLocal : model.SendDate.FullDate;
                        pn.Message   = model.Message;
                        pn.PlaySound = model.PlaySound;
                        pn.ConvertAllToUTC();
                    }
                    db.SaveChanges();
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError(string.Empty, ex.Message);
                }
            }

            return(ModelState.IsValid ?
                   Json(new { success = true }) :
                   Json(new { success = false, formWithErrorMessages = this.RenderPartialViewToString(MVC.PushNotification.Views.Edit, model) }));
        }
Exemplo n.º 21
0
        //Android push message to GCM server method
        #region IPushNotifier Implemented methods

        public void Invite(Event evnt, List <UserProfile> users)
        {
            List <string> registrationIds = new List <string>();

            users.ForEach(user =>
            {
                registrationIds.Add(user.GCMClientId);
            });
            GcmNotification notification = new GcmNotification();

            notification.ForDeviceRegistrationId(registrationIds);
            PushNotification notificationData = new PushNotification()
            {
                Type      = "EventInvite",
                EventId   = evnt.EventId.ToString(),
                EventName = evnt.Description
            };

            notification.WithJson(Serializer.SerializeToJason <PushNotification>(notificationData));

            this.PushNotification(notification);
        }
Exemplo n.º 22
0
        /// <summary>
        /// Called every time a remote message is received.
        /// </summary>
        /// <param name="remoteMessage">A remote firebase message. (https://firebase.google.com/docs/reference/android/com/google/firebase/messaging/RemoteMessage).</param>
        public override void OnMessageReceived(RemoteMessage remoteMessage)
        {
            var notification = remoteMessage.GetNotification();

            var title = notification?.Title;
            var body  = notification?.Body;

            PushNotification push = new PushNotification
            {
                Title    = title ?? string.Empty,
                Body     = body ?? string.Empty,
                Data     = new Dictionary <string, string>(remoteMessage.Data),
                Received = DateTimeOffset.Now
            };

            MainActivity.Receiver.Notify(push);

            if (remoteMessage.Data.Count >= 1)
            {
                SendNotification(push);
            }
        }
Exemplo n.º 23
0
        static void GoDirect(PushNotification push, string user)
        {
            try
            {
                var msg = push.Message;
                var act = push.IgAction;
                var img = push.OptionalAvatarUrl;
                if (msg.Contains("sent you a post") || msg.Contains("sent you a story"))
                {
                    if (msg.Contains(" "))
                    {
                        var name = msg.Substring(0, msg.IndexOf(" "));
                        var text = msg.Substring(msg.IndexOf(" ") + 1);
                        Notify.SendMessageWithoutTextNotify(/*$"[{user}] " + */ name, text, img, act, push.OptionalImage);
                    }
                    else
                    {
                        Notify.SendMessageWithoutTextNotify(null, /*$"[{user}] " + */ msg, img, act, push.OptionalImage);
                    }
                }
                else
                {
                    if (msg.Contains(":"))
                    {
                        var name = msg.Substring(0, msg.IndexOf(":"));

                        var text = msg.Substring(msg.IndexOf(":") + 1);

                        Notify.SendMessageNotify(/*$"[{user}] " +*/ name, text, img, act, push.OptionalImage);
                    }
                    else
                    {
                        Notify.SendMessageNotify(null, /* $"[{user}] " +*/ msg, img, act, push.OptionalImage);
                    }
                }
            }
            catch { }
        }
        /// <summary>
        /// Handles the notification to ensure the Notification manager is updated to alert the user
        /// </summary>
        private void SendNotification(PushNotification push)
        {
            // Create relevant non-repeatable Id to allow multiple notifications to be displayed in the Notification Manager
            Int32 notificationId = Int32.Parse(DateTime.Now.ToString("MMddHHmmsss"));

            Intent intent = new Intent(this, typeof(MainActivity));

            intent.AddFlags(ActivityFlags.ClearTop | ActivityFlags.SingleTop);
            intent.PutExtra("Area", push.Area);
            intent.PutExtra("ExtraInfo", push.ExtraInfo);

            PendingIntent pendingIntent = PendingIntent.GetActivity(this, notificationId, intent, PendingIntentFlags.UpdateCurrent);

            notificationManager = (NotificationManager)GetSystemService(Context.NotificationService);

            // Set BigTextStyle for expandable notifications
            NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
            bigTextStyle.SetSummaryText(push.Body);
            bigTextStyle.SetSummaryText(String.Empty);

            Int64 timestamp = DateTimeOffset.Now.ToUnixTimeMilliseconds();

            Notification notification = new NotificationCompat.Builder(this, NotificationChannelId)
                                        .SetSmallIcon(Resource.Drawable.ic_launcher)
                                        .SetContentTitle(push.Title)
                                        .SetContentText(push.Body)
                                        .SetStyle(bigTextStyle)
                                        .SetPriority(NotificationCompat.PriorityHigh)
                                        .SetWhen(timestamp)
                                        .SetShowWhen(true)
                                        .SetContentIntent(pendingIntent)
                                        .SetAutoCancel(true)
                                        .Build();

            notificationManager.Notify(notificationId, notification);

            notificationManager.Notify(notificationId, notification);
        }
        public async Task SHOULD_call_http_client_using_correct_endpoint_and_appname_and_Device_Ids_for_each_target_platform()
        {
            //Arrange
            var notification = new PushNotification
            {
                Title         = "Test",
                DeviceTargets = new List <PushNotificationTarget>
                {
                    new PushNotificationTarget {
                        TargetDevicePlatform = RuntimePlatform.UWP, TargetDeviceId = "1"
                    },
                    new PushNotificationTarget {
                        TargetDevicePlatform = RuntimePlatform.iOS, TargetDeviceId = "2"
                    },
                    new PushNotificationTarget {
                        TargetDevicePlatform = RuntimePlatform.iOS, TargetDeviceId = "3"
                    },
                }
            };


            //Act
            await Sut.SendPushNotificationAsync(notification, new TestConfig());

            //Assert
            _mockHttpClientService.Mock.Verify(x => x.PostAsync <AppCenterPushRequestDto, AppCenterPushResponseDto>(It.Is <IHttpRequestWrapper <AppCenterPushRequestDto> >(y =>
                                                                                                                                                                           y.Request.NotificationTarget.Devices.FirstOrDefault(a => a == "1") != null &&
                                                                                                                                                                           y.Request.NotificationTarget.Devices.FirstOrDefault(b => b == "2") == null &&
                                                                                                                                                                           y.Request.NotificationTarget.Devices.FirstOrDefault(c => c == "3") == null &&
                                                                                                                                                                           y.Endpoint == "https://api.appcenter.ms/v0.1/apps/organizationName/uwpAppName/push/notifications" &&
                                                                                                                                                                           y.RequestHeaders["X-API-Token"] == "apiToken"), CancellationToken.None));
            _mockHttpClientService.Mock.Verify(x => x.PostAsync <AppCenterPushRequestDto, AppCenterPushResponseDto>(It.Is <IHttpRequestWrapper <AppCenterPushRequestDto> >(y =>
                                                                                                                                                                           y.Request.NotificationTarget.Devices.FirstOrDefault(a => a == "1") == null &&
                                                                                                                                                                           y.Request.NotificationTarget.Devices.FirstOrDefault(b => b == "2") != null &&
                                                                                                                                                                           y.Request.NotificationTarget.Devices.FirstOrDefault(c => c == "3") != null &&
                                                                                                                                                                           y.Endpoint == "https://api.appcenter.ms/v0.1/apps/organizationName/iosAppName/push/notifications" &&
                                                                                                                                                                           y.RequestHeaders["X-API-Token"] == "apiToken"), CancellationToken.None));
        }
        /// <summary>
        /// Tries to create the <see cref="PushNotification"/> object from the details in <see cref="EventGridEvent"/> object. Return value indicates whether the operation succeeded or failed.
        /// </summary>
        /// <param name="eventGridEvent"> EventGridEvent from EventGrid</param>
        /// <param name="pushNotification"> If this method returns true, the pushNotification  object contains details populated from eventGridEvent. If this method returns false, the pushNotification object is null. </param>
        /// <returns></returns>
        public static bool TryCreatePushNotification(this EventGridEvent eventGridEvent, out PushNotification pushNotification)
        {
            pushNotification = null;

            if (eventGridEvent.Data == null || eventGridEvent.EventType == null || eventGridEvent.Subject == null)
            {
                return(false);
            }

            if (Uri.TryCreate(eventGridEvent.Subject, UriKind.Absolute, out Uri resourceUri))
            {
                JsonElement eventGridEventData;

                try
                {
                    eventGridEventData = JsonDocument.Parse(eventGridEvent.Data.ToString()).RootElement;
                }
                catch (JsonException)
                {
                    return(false);
                }

                if (eventGridEventData.ValueKind == JsonValueKind.Object &&
                    eventGridEventData.TryGetProperty(SyncTokenPropertyName, out JsonElement syncTokenJson) &&
                    syncTokenJson.ValueKind == JsonValueKind.String)
                {
                    pushNotification = new PushNotification()
                    {
                        SyncToken   = syncTokenJson.GetString(),
                        EventType   = eventGridEvent.EventType,
                        ResourceUri = resourceUri
                    };
                    return(true);
                }
            }

            return(false);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="pushNotifications"></param>
        public void Queue(PushNotification pushNotification)
        {
            var notificationData = new
            {
                //Base notification data
                title = pushNotification.Title,
                body  = pushNotification.Body,
                sound = "default"
            };

            var data         = JObject.FromObject(notificationData);
            var notification = JObject.FromObject(notificationData);

            notification.Add("click_action", "FCM_PLUGIN_ACTIVITY");

            this.QueueNotification(new GcmNotification()
            {
                To = !string.IsNullOrEmpty(pushNotification.Topic) ? string.Format("/topics/{0}", pushNotification.Topic) : null,
                RegistrationIds = pushNotification.Devices != null && pushNotification.Devices.Any() ? pushNotification.Devices : null,
                Notification    = notification,
                Data            = data
            });
        }
Exemplo n.º 28
0
        public async Task <JsonResult> SaveComment([FromBody] ImageComment comment)
        {
            _databaseConnection.Add(comment);
            _databaseConnection.SaveChanges();

            var image = _databaseConnection.Images.SingleOrDefault(n => n.ImageId == comment.ImageId);

            if (comment.ImageCommentId > 0)
            {
                if (image != null)
                {
                    var notification = new PushNotification
                    {
                        AppUserId        = image.AppUserId,
                        CreatedBy        = comment.CreatedBy,
                        LastModifiedBy   = comment.CreatedBy,
                        DateLastModified = DateTime.Now,
                        DateCreated      = DateTime.Now,
                        Category         = SystemNotificationCategory.Comment.ToString(),
                        Read             = false,
                        ControllerId     = image.ImageId,
                        ClientId         = 4
                    };

                    var singleOrDefault = new AppUserFactory()
                                          .GetAllUsers(new AppConfig().FetchUsersUrl).Result
                                          .SingleOrDefault(n => n.AppUserId == image.AppUserId);
                    if (singleOrDefault != null)
                    {
                        notification.Message = singleOrDefault.Name +
                                               " Commented on your Image";
                    }
                    await new AppUserFactory().SavePushNotification(new AppConfig().SavePushNotifications, notification);
                }
            }
            return(Json(comment));
        }
Exemplo n.º 29
0
        private async Task <bool> SendNotificationGuests(PushNotification pushNotification, int?anousmentId)
        {
            List <Guest> allGuests = await _repository.GetAll <Guest>().Include(s => s.PersonSettings).ToListAsync();

            foreach (var guest in allGuests)
            {
                var userLanguage = await _repository.FilterAsNoTracking <PersonOtherSetting>(x =>
                                                                                             x.GuestId == guest.Id).ToListAsync();

                if (guest.PersonSettings.Select(x => x.SubscriptionsType).Contains(SubscriptionsType.NewMessagesNotifications))
                {
                    _repository.Create(new PersonNotification
                    {
                        PushNotificationId = pushNotification.Id,
                        GuestId            = guest.Id,
                        AnnouncementId     = null
                    });
                    var lang = userLanguage.Select(l => l.Language).FirstOrDefault();
                    await _firebaseRepository.SendIndividualNotification(new FirebaseIndividualNotificationModel
                    {
                        Description = lang == Language.English ? pushNotification.Description :
                                      pushNotification.PushNotificationTranslates.Select(n => n.Description).FirstOrDefault(),
                        Title = lang == Language.English ? pushNotification.Title :
                                pushNotification.PushNotificationTranslates.Select(n => n.Title).FirstOrDefault(),
                        NotificationType           = NotificationType.PushNotification,
                        PushNotificationActionType = pushNotification.PushNotificationActionType,
                        FromAdmin  = true,
                        SenderId   = null,
                        ReceiverId = guest.Id,
                        GenericId  = anousmentId.HasValue ? anousmentId.Value : 0
                    }, true);
                }
            }
            await _repository.SaveChangesAsync();

            return(true);
        }
Exemplo n.º 30
0
        public async Task UpdateExpiredRidesAndOrders_WhenCalled_SavesChanges()
        {
            var _unitOfWork = NSubstitute.Substitute.For <IUnitOfWork>();

            //Create
            var orderList = new List <Order>();
            var order     = new Order();
            var ride      = new Ride();

            //Set
            ride.StartDestination = new Address("city", 1000, "street", 1);
            ride.EndDestination   = new Address("city", 1000, "street", 1);
            order.Rides.Add(ride);
            orderList.Add(order);
            //Create and set
            var rideList = new List <Ride>();

            rideList.Add(ride);

            //Stub out
            _unitOfWork.OrderRepository.FindOrdersWithExpiredRides().ReturnsForAnyArgs(orderList);
            _unitOfWork.RideRepository.FindExpiredUnmatchedRides().ReturnsForAnyArgs(rideList);


            var push    = Substitute.For <IPushNotificationFactory>();
            var pushNot = new PushNotification();

            //VERY Important that push notification gets a new otherwise it will throw misleading exception
            //For all. So 1 order with 1 ride, and 1 ride. aka two.
            push.GetPushNotification().ReturnsForAnyArgs(new PushNotification(), new PushNotification());
            var center = Substitute.For <IPushNotificationService>();

            IExpirationService _uut = new ExpirationService(_unitOfWork, push, center);
            await _uut.UpdateExpiredRidesAndOrders();

            _unitOfWork.Received(1).SaveChangesAsync();
        }
Exemplo n.º 31
0
        public override SendResponse ProcessMessage(INoticeMessage message)
        {
            try
            {
                var notification = new PushNotification
                {
                    Module       = GetTagValue <PushModule>(message, PushConstants.PushModuleTagName),
                    Action       = GetTagValue <PushAction>(message, PushConstants.PushActionTagName),
                    Item         = GetTagValue <PushItem>(message, PushConstants.PushItemTagName),
                    ParentItem   = GetTagValue <PushItem>(message, PushConstants.PushParentItemTagName),
                    Message      = message.Body,
                    ShortMessage = message.Subject
                };

                if (IsServiceConfigured)
                {
                    using (var pushClient = new PushServiceClient())
                    {
                        pushClient.EnqueueNotification(
                            CoreContext.TenantManager.GetCurrentTenant().TenantId,
                            message.Recipient.ID,
                            notification,
                            new List <string>());
                    }
                }
                else
                {
                    _log.Debug("push sender endpoint is not configured!");
                }

                return(new SendResponse(message, Constants.NotifyPushSenderSysName, SendResult.OK));
            }
            catch (Exception error)
            {
                return(new SendResponse(message, Constants.NotifyPushSenderSysName, error));
            }
        }
Exemplo n.º 32
0
        public ActionResult Cms()
        {
            if (Session["UserName"] != null)
            {
                ViewBag.Title = "Content Managemnent";
                MenuAndContent mC = new MenuAndContent(System.Web.HttpContext.Current.Session["LanguageVar"].ToString());
                AllClasses     aC = new AllClasses();
                aC.MenuandContent = mC;
                ContentManagements Cms = new BusinessLogic().Cms();
                ContentManagement  cMs = new ContentManagement();
                cMs.TermsAndConditions = Cms != null ? Cms.TermsAndConditions : "";
                cMs.PrivacyAndPolicy   = Cms != null ? Cms.PrivacyAndPolicy : "";
                aC.ContentManagement   = cMs;

                List <PushNotifications> pN = new BusinessLogic().AllPN();
                List <PushNotification>  Pn = new List <PushNotification>();
                if (pN != null)
                {
                    foreach (var dfr in pN)
                    {
                        PushNotification i = new PushNotification();
                        i.id    = dfr.id;
                        i.Title = dfr.Title;
                        i.Descp = dfr.Descp;
                        Pn.Add(i);
                    }
                }

                aC.PushNotifications = Pn;

                return(View("Cms", aC));
            }
            else
            {
                return(RedirectToAction("Index", "User"));
            }
        }
        public async Task SendAsync(PushNotification notification)
        {
            if (notification == null)
            {
                throw new ArgumentNullException(nameof(notification));
            }

            lock (_lockObject)
            {
                var alreadyExistNotify = _innerList.FirstOrDefault(x => x.Id == notification.Id);
                if (alreadyExistNotify != null)
                {
                    _innerList.Remove(alreadyExistNotify);
                    _innerList.Add(notification);
                }
                else
                {
                    var lastEvent = _innerList.OrderByDescending(x => x.Created).FirstOrDefault();
                    if (lastEvent != null && lastEvent.ItHasSameContent(notification))
                    {
                        lastEvent.IsNew = true;
                        lastEvent.RepeatCount++;
                        lastEvent.Created = DateTime.UtcNow;
                    }
                    else
                    {
                        _innerList.Add(notification);
                    }
                }
            }

            if (_hubContext != null)
            {
                await _hubContext.Clients.All.SendCoreAsync("Send", new[] { notification });
            }
        }
Exemplo n.º 34
0
        /// <summary>
        /// Handles the notification to ensure the Notification manager is updated to alert the user.
        /// </summary>
        /// <param name="push">Helper method to display the received push notification on the device.</param>
        private void SendNotification(PushNotification push)
        {
            var intent = new Intent(this, typeof(MainActivity));

            intent.AddFlags(ActivityFlags.ClearTop | ActivityFlags.SingleTop);
            intent.PutExtra("Title", push.Title);
            intent.PutExtra("Body", push.Body);

            var notificationId = int.Parse(DateTime.Now.ToString("MMddHHmmsss"));

            PendingIntent pendingIntent =
                PendingIntent.GetActivity(this, notificationId, intent, PendingIntentFlags.UpdateCurrent);

            _notificationManager = (NotificationManager)GetSystemService(Context.NotificationService);

            // Set BigTextStyle for expandable notifications
            NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
            bigTextStyle.SetSummaryText(push.Body);
            bigTextStyle.SetSummaryText(string.Empty);

            long timestamp = DateTimeOffset.Now.ToUnixTimeMilliseconds();

            Notification notification = new NotificationCompat.Builder(this, NotificationChannelId)
                                        .SetSmallIcon(Resource.Drawable.ably_logo)
                                        .SetContentTitle(push.Title)
                                        .SetContentText(push.Body)
                                        .SetStyle(bigTextStyle)
                                        .SetPriority(NotificationCompat.PriorityHigh)
                                        .SetWhen(timestamp)
                                        .SetShowWhen(true)
                                        .SetContentIntent(pendingIntent)
                                        .SetAutoCancel(true)
                                        .Build();

            _notificationManager?.Notify(notificationId, notification);
        }
        public async Task <IActionResult> SendPushNotification(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "push/notification")]
            [RequestBodyType(typeof(PushNotification), "Send push notification")] HttpRequest request)
        {
            var validateStatus = base.AuthorizationStatus(request);

            if (validateStatus != HttpStatusCode.Accepted)
            {
                return(new BadRequestObjectResult(validateStatus));
            }

            string           requestBody = await new StreamReader(request.Body).ReadToEndAsync();
            PushNotification requestData = JsonConvert.DeserializeObject <PushNotification>(requestBody);

            try
            {
                await _notification.SendAsync(requestData);
            }
            catch (HttpResponseException ex)
            {
                return(new BadRequestObjectResult(ex));
            }
            return(new OkObjectResult(new { message = "Push notification send successfully." }));
        }
Exemplo n.º 36
0
        public Boolean NotifyRemoveParticipantFromEvent(Event evt, List <string> removedParticipantGcms)
        {
            try
            {
                if (removedParticipantGcms.Count == 0)
                {
                    return(true);
                }

                PushNotification pn = GetMessage(evt, "RemovedFromEvent");

                removedParticipantGcms = validateGcmIds(removedParticipantGcms);
                new NotificationTaskManager(new NotificationContainer()
                {
                    RegistrationIds = removedParticipantGcms, NotificationData = pn
                }).Enqueue();
                //this.notifier.SendInvite(registrationIds, pn);
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Exemplo n.º 37
0
        public void SerializerRawPushNotificationTest()
        {
            var msg = PushNotification
                      .Broadcast("This is a test message.")
                      .WithBadge("+1")
                      .WithExpiry(100000)
                      .WithPlatformOptions(new IOsOptions {
                SoundFile = "soundfile"
            })
                      .WithPlatformOptions(new AndroidOptions {
                NotificationTitle = "title"
            })
                      .WithPlatformOptions(
                new WindowsPhoneOptions
            {
                Notification = new RawNotification
                {
                    RawData = "raw string data.."
                }
            });
            var serializer = ObjectFactory.Build <IJsonSerializer>();

            Console.WriteLine(Encoding.UTF8.GetString(serializer.Serialize(msg)));
        }
		public void OnError (string message, PushNotification.Plugin.Abstractions.DeviceType deviceType)
		{
			Console.WriteLine (message);
		}
		public void OnUnregistered (PushNotification.Plugin.Abstractions.DeviceType deviceType)
		{
			Console.WriteLine ("Unregistered");
		}
		public async void OnRegistered (string Token, PushNotification.Plugin.Abstractions.DeviceType deviceType)
		{
			await TinyIoC.TinyIoCContainer.Current.Resolve<IApiService> ().RegisterDeviceAsync ("android", Token);
			Console.WriteLine ("Registered");

		}
		public async void OnMessage (Newtonsoft.Json.Linq.JObject values, PushNotification.Plugin.Abstractions.DeviceType deviceType)
		{
			
			Console.WriteLine ("Message Received");
		}
Exemplo n.º 42
0
 public abstract Validation CheckRule(TeamFoundationRequestContext requestContext, PushNotification pushNotification, TfsGitRepository repository);
Exemplo n.º 43
0
    public JsonResult SetNotification(PushNotification notification, string oper)
    {
        string cn = UmbracoCustom.GetParameterValue(UmbracoType.Connection);

        switch (oper)
        {
            case "add":
                NameValueCollection nameValueCollection = HttpUtility.ParseQueryString(Request.UrlReferrer.Query);
                int memberId = int.Parse(nameValueCollection["id"]);
                Member member = new Member(memberId);
                SqlHelper.ExecuteNonQuery(cn, CommandType.StoredProcedure, "InsertNotification",
                    new SqlParameter { ParameterName = "@Id", Value = notification.Id, Direction = ParameterDirection.Output, SqlDbType = SqlDbType.Int },
                    new SqlParameter { ParameterName = "@MemberId", Value = member.Id, Direction = ParameterDirection.Input, SqlDbType = SqlDbType.Int },
                    new SqlParameter { ParameterName = "@Token", Value = notification.Token, Direction = ParameterDirection.Input, SqlDbType = SqlDbType.VarChar, Size = 50 },
                    new SqlParameter { ParameterName = "@DeviceId", Value = int.Parse(notification.Device), Direction = ParameterDirection.Input, SqlDbType = SqlDbType.Int }
                    );
                break;
            case "edit":
                SqlHelper.ExecuteNonQuery(cn, CommandType.StoredProcedure, "UpdateNotification",
                    new SqlParameter { ParameterName = "@Id", Value = notification.Id, Direction = ParameterDirection.Input, SqlDbType = SqlDbType.Int },
                    new SqlParameter { ParameterName = "@Token", Value = notification.Token, Direction = ParameterDirection.Input, SqlDbType = SqlDbType.VarChar, Size = 50 },
                    new SqlParameter { ParameterName = "@DeviceId", Value = int.Parse(notification.Device), Direction = ParameterDirection.Input, SqlDbType = SqlDbType.Int },
                    new SqlParameter { ParameterName = "@IsActive", Value = notification.IsActive, Direction = ParameterDirection.Input, SqlDbType = SqlDbType.Bit }
                    );
                break;
            case "del":
                break;

        }
        return Json("Success Save");
    }
 private void WriteData(JsonWriter writer, PushNotification push)
 {
     writer.WritePropertyName("data");
     writer.StartObject();
     writer
         .WriteProperty("alert", push.Alert)
         .WriteProperty("badge", push.Badge, true);
     foreach (var key in push.Data.Keys)
     {
         if (key.Equals("alert", StringComparison.OrdinalIgnoreCase) == true ||
             key.Equals("badge", StringComparison.OrdinalIgnoreCase) == true)
             continue;
         writer.WriteProperty(key, push.Data[key]);
     }
     writer.EndObject();
 }
 public void OnRegistered(string token, PushNotification.Plugin.Abstractions.DeviceType deviceType)
 {
     DeviceToken = token;
 }
        public void OnUnregistered(PushNotification.Plugin.Abstractions.DeviceType deviceType)
        {

        }
Exemplo n.º 47
0
        public string PushNotificationData()
        {
            string value = "{}";
            PushNotification obj = new PushNotification();
            PushNotificationInfo info = new PushNotificationInfo();
            string[] channels = { "" };
            obj.channels = channels;

            info.alert = "https://www.Google.co.in#VKulkarni";
            info.sound = "I am ready";
            info.title = "I am not ready";
            //info.action = "android.intent.action.FIRE_LINK";
            obj.data = info;
            value = JsonConvert.SerializeObject(obj);
            return value;
        }
Exemplo n.º 48
0
        private string CommitToString(TeamFoundationRequestContext requestContext, TfsGitCommit gitCommit, string action, PushNotification pushNotification, 
            Dictionary<byte[], List<string>> refNames)
        {
            DateTime authorTime = gitCommit.GetLocalAuthorTime(requestContext);
            string authorName = gitCommit.GetAuthor(requestContext);
            string comment = gitCommit.GetComment(requestContext);
            StringBuilder sb = new StringBuilder();
            List<string> names = null;
            if (refNames.TryGetValue(gitCommit.ObjectId, out names)) sb.AppendFormat("{0} ", String.Join("", names));
            sb.AppendFormat("{0} {1} {2} {3} {4}", action, gitCommit.ObjectId.ToShortHexString(), authorTime.ToString(), authorName,
                comment.Truncate(COMMENT_MAX_LENGTH));

            return sb.ToString();
        }
        private string GetEmailAddress(TeamFoundationRequestContext requestContext, PushNotification pushNotification)
        {
            var collectionUrl = new Uri(requestContext.GetCollectionUri());
            var collection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(collectionUrl);
            var managementService = collection.GetService<IIdentityManagementService>();
            TeamFoundationIdentity teamFoundationIdentity = managementService.ReadIdentity(
                    IdentitySearchFactor.AccountName,
                    pushNotification.AuthenticatedUserName,
                    MembershipQuery.None,
                    ReadIdentityOptions.None);

            return teamFoundationIdentity.GetAttribute("Mail", null);
        }
Exemplo n.º 50
0
        /// <summary>
        /// Send a push notification to Parse.com
        /// </summary>
        /// <param name="notification">The notification to send</param>
        /// <returns>True if message was send successfully</returns>
        private bool SendPushNotification(PushNotification.Model.Notification notification)
        {
            string responseData;

            if (!PushEnabled.HasValue || !PushEnabled.Value)
            {
                return false;
            }
            
            // call the web client manager to post the data to Parse.com
            var success = pushNotificationGateway.SendPushNotification(notification, out responseData);

            // if the push notification failed for some reason then create a business event
            if (!success)
            {
                // Create event
                eventTrackingManager.CreateBusinessEventAsync(notification.Data.BusinessId, BusinessEventTypesEnum.PushNotificationFailure, notification.Data.Reference, responseData);
            }

            return success;
        }
 public void OnMessage(IDictionary<string, object> parameters, PushNotification.Plugin.Abstractions.DeviceType deviceType)
 {
     //handle push notifications here
 }
Exemplo n.º 52
0
    /// <summary>
    /// Initialize a connection the the Apple Push Notification Service (APNS) and deliver a new deal notification
    /// payload to all registered devices in the database.
    /// </summary>
    /// <param name="currentHeadline">The headline to be sent in the push notification payload</param>
    private void SendNotifications(int id, string headline)
    {
        //configure and start Apple APNS
        PushNotification push;
        try {
            push = new PushNotification(false, Path.Combine(AppDomain.CurrentDomain.BaseDirectory, this.key), ConfigurationManager.AppSettings["certPassword"]);
        }
        catch (Exception e) {
            LogError("!Failed to start service.", e);
            return;
        }

        IList<DeviceToken> deviceTokens = null;
        try {
            //get a list of all registered device tokens
            using (PushModelContainer context = new PushModelContainer())
            {
                var q = (from dt in context.DeviceTokens
                         //where dt.Development.Equals(true)
                         where dt.Development.Equals(this.isDevelopment)
                         where dt.AppName.Equals(this.appName)
                         where dt.Active.Equals(true)
                         select dt);
                deviceTokens = q.ToList<DeviceToken>();

                foreach (DeviceToken deviceToken in deviceTokens) {
                    if (deviceToken.BadgeCount > 50) {
                        deviceToken.BadgeCount = 0;
                    } else {
                        deviceToken.BadgeCount++;
                    }
                }

                context.SaveChanges();
            }
        }
        catch (Exception e) {
            LogError("!Failed to fetch device tokens.", e);
            return;
        }

        //hold a list of payloads to be pushed
        var payloads = new List<NotificationPayload> {};

        //loop for every registered device token
        foreach (DeviceToken deviceToken in deviceTokens) {
            //add the payload to the list
            var payload = new NotificationPayload(deviceToken.Token, ModifyHeadline(headline), deviceToken.BadgeCount, "default");
            payload.AddCustom("id", id);
            payloads.Add(payload);
        }

        //send the payloads and get a list of rejected payloads for deletion
        Logger.Info(@" >Delivering payloads...");
        var rejectedTokens = push.SendToApple(payloads);
        if (rejectedTokens.Count > 0) {
            //deactivate all rejected device tokens
            using (PushModelContainer context = new PushModelContainer())
            {
                foreach (var rejectedToken in rejectedTokens) {
                    Logger.Warn(@"Deactivating token: " + rejectedToken);

                    DeviceToken deviceToken = (from dt in context.DeviceTokens
                                               where dt.Token.Equals(rejectedToken)
                                               select dt).FirstOrDefault();
                    if (deviceToken != null) {
                        deviceToken.Active = false;
                    }
                }
                context.SaveChanges();
            }
        }
        Logger.Info(@" >All payloads delivered.");
        Logger.Info(@"");
    }
 public void OnError(string message, PushNotification.Plugin.Abstractions.DeviceType deviceType)
 {
     Console.WriteLine("A notifications error occured: {0} ", message);
 }
        private Policy GetPolicy(TeamFoundationRequestContext requestContext, PushNotification pushNotification)
        {
            // HACK
            string collectionName = requestContext.ServiceHost.VirtualDirectory.Replace("/tfs/", "").Replace("/", "");
            // HACK is this cheap?
            var commonService = requestContext.GetService<CommonStructureService>();
            string projectName = commonService.GetProject(requestContext, pushNotification.TeamProjectUri).Name;
            string repositoryName = pushNotification.RepositoryName;

            foreach (var policy in PluginConfiguration.Instance.Policies)
            {
                if (policy.AppliesTo(collectionName, projectName, repositoryName))
                    return policy;
            }//for

            return null;
        }
    void GetPlayerDetails()
    {
        if (FB.IsLoggedIn)
        {
            // AccessToken class will have session details
            var aToken = Facebook.Unity.AccessToken.CurrentAccessToken;

            PlayerPrefs.SetString("UserId",aToken.UserId );
            // Print current access token's User ID
            if(Application.loadedLevelName == "Menu")
            {
                GetFirstName();
                //GetUserID ();

                PushNotification Pushnoti = new PushNotification ();
                Pushnoti.InitiatePush ();

                //GetProfilePicture();
            }
            Debug.Log("Token - " + aToken );
            // Print current access token's granted permissions
        }
        else{
            Debug.Log("Shitn - "  );
        }
    }