public void Simple()
        {
            var service = new PushService
            {
                RequestBuilder = RequestBuilderHelper.Build()
            };
            var pushNotification = new PushNotificationRequest
            {
                DeviceTokens = new List <string>
                {
                    RemoteSettings.AppleDeviceId
                },
                Payload = new PushPayload
                {
                    Alert = "Alert"
                },
                CustomData = new Dictionary <string, string>
                {
                    { "Key", "Value" }
                }
            };

            var asyncTestHelper = new AsyncTestHelper();

            service.Execute(pushNotification, response => asyncTestHelper.Callback(null), asyncTestHelper.HandleException);
            asyncTestHelper.Wait();
        }
示例#2
0
        /// <summary>
        /// For Pushing Notifications
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public PushNotificationResponse PushNotification(PushNotificationRequest request)
        {
            PushNotificationResponse response = new PushNotificationResponse();

            pushNotificationRepository.PushNotifications(request.PushNotification);
            return(response);
        }
示例#3
0
        public override async Task SendPushNotificationTokenAsync(string token, CancellationToken cancellationToken)
        {
            AmazonS3Client s3 = null;

            try
            {
                s3 = await CreateS3ClientAsync();

                // get the token JSON payload
                PushNotificationRequestFormat localFormat = PushNotificationRequest.LocalFormat;
                string localFormatAzureIdentifier = PushNotificationRequest.GetAzureFormatIdentifier(localFormat);
                byte[] tokenBytes = Encoding.UTF8.GetBytes("{" +
                                                             "\"device\":" + JsonConvert.ToString(SensusServiceHelper.Get().DeviceId) + "," + 
                                                             "\"protocol\":" + JsonConvert.ToString(Protocol.Id) + "," + 
                                                             "\"format\":" + JsonConvert.ToString(localFormatAzureIdentifier) + "," +
                                                             "\"token\":" + JsonConvert.ToString(token) +
                                                           "}");
                                                            
                MemoryStream dataStream = new MemoryStream(tokenBytes);

                await PutAsync(s3, dataStream, GetPushNotificationTokenKey(), "application/json", cancellationToken);
            }
            finally
            {
                DisposeS3(s3);
            }
        }
        public void Simple()
        {
            var service = new PushService
            {
                RequestBuilder = ServerRequestBuilder.Instance
            };
            var notification = new PushNotificationRequest
            {
                Tags = new List <string> {
                    "MyTag"
                },
                ExcludeTokens = new List <string> {
                    "TokenToExclude"
                },
                DeviceTokens = new List <string> {
                    "AppleDeviceId"
                },
                Aliases = new List <string> {
                    "MyAlias"
                },
                Payload = new PushPayload
                {
                    Alert = "Alert 2",
                    Badge = Badge.SetTo(2),
                    Sound = "Sound1"
                }
            };

            service.Execute(notification, response => Debug.WriteLine("Success"), ExceptionHandler.Handle);
        }
        public async Task SendPushNotification_GIVEN_Valid_Inputs_RETURNS_Valid_PushNotificationResponse_SuccessFalse()
        {
            // Arrange.
            var settings = Substitute.For <ISettings>();

            settings["PushNotification:Url"] = "https://www.test.com";

            var tokenType   = "bearer";
            var accessToken =
                "nV7-QR3si92u5H4rhGMRDDg-Z8b_cXpDbHekAmKFkTQjqnrtZcwURtXDVnHKUa4dnFdr29iznAkMMBWSZOeaCXAHVTYZGaaxC7hD0XHWIo5Cj8-QIiRndFrHA8GYDoqZ5sHE9-tnfbvTp6OXSI3CcTpqh95UrZCPsyRFe8SfheEvIPf018vGTgtU1_GBytePe5iINI_bw67ohkFmDXvVIZ2ym6_UXBCdXQPthorSMAiq14o8C-Mqxqc90P0pj_kNvbch2L2Ur4NWS56T_HtUpDV93ZVytR2b2e9c7USAnSAoL7P77REqBpINoKnNj62iZAsPqq22acM2nl5jv-rDoUYhxGb28P_jRq_-iiC2RG-L9_mnzv_S6saZs7m5zsPe_h_omyY1hMlQTvXwb0xYzLNHwjy_5TkAkah_-Gegutka29dKkSyAhWqlZy96-9J48SOgmtXsA1pyMbsZIDPal2ymUZiRyQe9BiiXGcQcsbneFeJbK1eKr7CIavmmpniM";
            var authorizationHeader = new AuthenticationHeaderValue(tokenType.Trim(), accessToken);

            var pushNotificationRequest = new PushNotificationRequest
            {
                IdNumber = "9009165023080",
                Title    = "Test Title",
                Message  = "Test Message"
            };

            var httpClientOperations = Substitute.For <IHttpClientOperations>();

            httpClientOperations.SendHttpRequestAsync(HttpMethod.Post, authorizationHeader, Arg.Any <Dictionary <string, string> >(),
                                                      "https://www.test.com", Arg.Any <HttpContent>(), CancellationToken.None).Returns(Task.FromResult("{\r\n    \"success\": false,\r\n    \"message\": \"Could not find user with ID Number: 9009165023080\"\r\n}"));

            var pushNotificationService = new PushNotificationService(httpClientOperations, settings);

            // Act.
            var actual = await pushNotificationService.SendPushNotification(accessToken, tokenType, pushNotificationRequest, CancellationToken.None);

            // Assert.
            Assert.IsNotNull(actual);
            Assert.AreEqual(false, actual.Success);
            Assert.AreEqual("Could not find user with ID Number: 9009165023080", actual.Message);
        }
        public async Task SendPushNotification_GIVEN_Invalid_Message_RETURNS_Null(string message)
        {
            // Arrange.
            var settings = Substitute.For <ISettings>();

            settings["PushNotification:Url"] = "https://www.test.com";

            var tokenType   = "bearer";
            var accessToken =
                "nV7-QR3si92u5H4rhGMRDDg-Z8b_cXpDbHekAmKFkTQjqnrtZcwURtXDVnHKUa4dnFdr29iznAkMMBWSZOeaCXAHVTYZGaaxC7hD0XHWIo5Cj8-QIiRndFrHA8GYDoqZ5sHE9-tnfbvTp6OXSI3CcTpqh95UrZCPsyRFe8SfheEvIPf018vGTgtU1_GBytePe5iINI_bw67ohkFmDXvVIZ2ym6_UXBCdXQPthorSMAiq14o8C-Mqxqc90P0pj_kNvbch2L2Ur4NWS56T_HtUpDV93ZVytR2b2e9c7USAnSAoL7P77REqBpINoKnNj62iZAsPqq22acM2nl5jv-rDoUYhxGb28P_jRq_-iiC2RG-L9_mnzv_S6saZs7m5zsPe_h_omyY1hMlQTvXwb0xYzLNHwjy_5TkAkah_-Gegutka29dKkSyAhWqlZy96-9J48SOgmtXsA1pyMbsZIDPal2ymUZiRyQe9BiiXGcQcsbneFeJbK1eKr7CIavmmpniM";

            var pushNotificationRequest = new PushNotificationRequest
            {
                IdNumber = "9009165023080",
                Title    = "Test Title",
                Message  = message
            };

            var httpClientOperations    = Substitute.For <IHttpClientOperations>();
            var pushNotificationService = new PushNotificationService(httpClientOperations, settings);

            // Act.
            var actual = await pushNotificationService.SendPushNotification(accessToken, tokenType, pushNotificationRequest, CancellationToken.None);

            // Assert.
            Assert.IsNull(actual);
        }
        public async Task <NotificationOutcome> PushNotification(PushNotificationRequest pushRequest)
        {
            // Sending the message so that all template registrations that contain "messageParam", "silentMessageParam", or "actionParam"
            // will receive the notifications. This includes APNS, GCM, WNS, and MPNS template registrations.
            Dictionary <string, string> templateParams = new Dictionary <string, string>();

            if (pushRequest.Silent)
            {
                templateParams["silentMessageParam"] = "1";
                templateParams["actionParam"]        = pushRequest.Action;
            }
            else
            {
                templateParams["message"] = pushRequest.Text;
            }
            try
            {
                // Send the push notification and log the results.
                var result = await _hubClient.SendTemplateNotificationAsync(templateParams, string.Join(" || ", pushRequest.Tags));

                return(result);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
示例#8
0
        /// <summary>
        /// Send push notification to client app
        /// </summary>
        /// <param name="model">Push information</param>
        /// <returns>Task no return</returns>
        public async Task SendPush(PushNotificationRequest model)
        {
            try
            {
                var userDevices = await this._deviceRepository.GetAllByUsernameAsync(model.Username);

                var iosDevices     = userDevices.Where(x => x.DeviceType == Core.Enumerations.DeviceType.IOS).ToList();
                var androidDevices = userDevices.Where(x => x.DeviceType == Core.Enumerations.DeviceType.Android).ToList();

                if (iosDevices.Count > 0)
                {
                    var pushData = new PushNotificationModel
                    {
                        Type         = model.Type,
                        Message      = model.Message,
                        DeviceTokens = iosDevices.Select(x => x.DeviceToken).ToList()
                    };

                    var result = this._applePushService.SendPushNotification(pushData);

                    this._logger.LogInformation(result);
                }
            }
            catch
            {
                throw;
            }
        }
示例#9
0
        public async Task <IActionResult> Push([FromBody] PushNotificationRequest request)
        {
            try
            {
                await this._deviceService.SendPush(request);

                return(this.Ok());
            }
            catch (Exception ex)
            {
                this._logger.LogError(ex, ex.Message);

                throw ex;
            }
        }
        public async Task <IActionResult> PushNotification([FromBody] PushNotificationRequest pushRequest)
        {
            try
            {
                logger.LogInformation("Push Notification called message {message}, tags- {tags}", pushRequest.Text, pushRequest.Tags);
                await _notificationHubRepo.PushNotification(pushRequest);

                return(Ok());
            }
            catch (Exception e)
            {
                logger.LogError(e, "Push Notification called Exceptionfor messagebody - {body}, tags- {tags}", pushRequest.Text, pushRequest.Tags);
                throw;
            }
        }
示例#11
0
        public void Single()
        {
            var notification = new PushNotificationRequest
            {
                Payload = new PushPayload
                {
                    Alert = "My Alert",
                    Sound = "My Sound",
                    Badge = Badge.Increment()
                },
                Aliases = new List <string> {
                    "alias1"
                },
                Tags = new List <string> {
                    "tag1"
                },
                DeviceTokens = new List <string> {
                    "token1"
                },
                ExcludeTokens = new List <string> {
                    "exclude1"
                },
            };
            var text     = notification.Serialize().FormatAsJson();
            var expected = @"
{
  'aps': {
    'alert': 'My Alert',
    'badge': '+1',
    'sound': 'My Sound'
  },
  'device_tokens': [
    'token1'
  ],
  'aliases': [
    'alias1'
  ],
  'tags': [
    'tag1'
  ],
  'exclude_tokens': [
    'exclude1'
  ]
}".Replace("\r\n", "\n");

            Assert.AreEqual(expected, text);
        }
示例#12
0
        public PushNotificationAction Handle(PushNotificationRequest command)
        {
            try
            {
                var           data     = command.Attributes;
                var           username = data["u"];
                var           repoId   = new RepositoryIdentifier(data["r"]);
                BaseViewModel baseViewModel;

                if (data.ContainsKey("c"))
                {
                    baseViewModel = _serviceConstructor
                                    .Construct <CommitViewModel>()
                                    .Init(repoId.Owner, repoId.Name, data["c"]);
                }
                else if (data.ContainsKey("i"))
                {
                    baseViewModel = _serviceConstructor
                                    .Construct <CodeHub.Core.ViewModels.Issues.IssueViewModel>()
                                    .Init(repoId.Owner, repoId.Name, int.Parse(data["i"]));
                }
                else if (data.ContainsKey("p"))
                {
                    baseViewModel = _serviceConstructor
                                    .Construct <CodeHub.Core.ViewModels.PullRequests.PullRequestViewModel>()
                                    .Init(repoId.Owner, repoId.Name, int.Parse(data["p"]));
                }
                else
                {
                    baseViewModel = _serviceConstructor
                                    .Construct <CodeHub.Core.ViewModels.Repositories.RepositoryViewModel>()
                                    .Init(repoId.Owner, repoId.Name);
                }

                return(new PushNotificationAction(username, baseViewModel));
            }
            catch (Exception e)
            {
                this.Log().ErrorException("Unable to handle push notification", e);
                return(null);
            }
        }
示例#13
0
        public PushNotificationAction Handle(PushNotificationRequest command)
        {
            try
            {
                var data = command.Attributes;
                var username = data["u"];
                var repoId = new RepositoryIdentifier(data["r"]);
                BaseViewModel baseViewModel;

                if (data.ContainsKey("c"))
                {
                    baseViewModel = _serviceConstructor
                        .Construct<CommitViewModel>()
                        .Init(repoId.Owner, repoId.Name, data["c"]);
                }
                else if (data.ContainsKey("i"))
                {
                    baseViewModel = _serviceConstructor
                        .Construct<CodeHub.Core.ViewModels.Issues.IssueViewModel>()
                        .Init(repoId.Owner, repoId.Name, int.Parse(data["i"]));
                }
                else if (data.ContainsKey("p"))
                {
                    baseViewModel = _serviceConstructor
                        .Construct<CodeHub.Core.ViewModels.PullRequests.PullRequestViewModel>()
                        .Init(repoId.Owner, repoId.Name, int.Parse(data["p"]));
                }
                else
                {
                    baseViewModel = _serviceConstructor
                        .Construct<CodeHub.Core.ViewModels.Repositories.RepositoryViewModel>()
                        .Init(repoId.Owner, repoId.Name);
                }

                return new PushNotificationAction(username, baseViewModel);
            }
            catch (Exception e)
            {
                this.Log().ErrorException("Unable to handle push notification", e);
                return null;
            }
        }
示例#14
0
        public void ToTag()
        {
            var service = new PushService
            {
                RequestBuilder = RequestBuilderHelper.Build()
            };
            var pushNotification = new PushNotificationRequest
            {
                Tags = new List <string> {
                    "africa"
                },
                Payload = new PushPayload
                {
                    Alert = "Alert 2"
                }
            };
            var asyncTestHelper = new AsyncTestHelper();

            service.Execute(pushNotification, x => asyncTestHelper.Callback(null), asyncTestHelper.HandleException);
            asyncTestHelper.Wait();
        }
示例#15
0
        public void Simple()
        {
            var service = new PushService
            {
                RequestBuilder = RequestBuilderHelper.Build()
            };
            var pushNotification = new PushNotificationRequest
            {
                PushIds = new List <string> {
                    RemoteSettings.AndroidPushId
                },
                Payload = new PushPayload
                {
                    Alert = "Alert 2"
                }
            };
            var asyncTestHelper = new AsyncTestHelper();

            service.Execute(pushNotification, x => asyncTestHelper.Callback(null), asyncTestHelper.HandleException);
            asyncTestHelper.Wait();
        }
示例#16
0
        public void Simple()
        {
            var service = new PushService
            {
                RequestBuilder = ServerRequestBuilder.Instance
            };
            var notification = new PushNotificationRequest
            {
                Tags = new List <string> {
                    "MyTag"
                },
                PushIds = new List <string> {
                    "AndroidPushId"
                },
                Payload = new PushPayload
                {
                    Alert = "Alert 2"
                }
            };

            service.Execute(notification, response => Debug.WriteLine("Success"), ExceptionHandler.Handle);
        }
示例#17
0
        public void Single()
        {
            var notification = new PushNotificationRequest
            {
                Payload = new PushPayload
                {
                    Alert = "My Alert",
                    Extra = new Dictionary <string, string>
                    {
                        { "a", "b" }
                    },
                },
                Aliases = new List <string> {
                    "alias1"
                },
                Tags = new List <string> {
                    "tag1"
                },
            };
            var text     = notification.Serialize().FormatAsJson();
            var expected = @"
{
  'android': {
    'alert': 'My Alert',
    'extra': {
      'a': 'b'
    }
  },
  'aliases': [
    'alias1'
  ],
  'tags': [
    'tag1'
  ]
}".Replace("\r\n", "\n");

            Assert.AreEqual(expected, text);
        }
示例#18
0
        public override async Task SendPushNotificationRequestAsync(PushNotificationRequest request, CancellationToken cancellationToken)
        {
            AmazonS3Client s3 = null;

            try
            {

#if __IOS__
                // the current method is called in response to push notifications when starting the protocol after the app 
                // has been terminated. starting the protocol may involve a large number of callbacks, particularly for 
                // surveys scheduled many times into the future. sending the associated push notification requests can be 
                // very time consuming. we need to be sensitive to the alotted background execution time remaining so that
                // the protocol can start fully before background time expires. we don't want to run afoul of background 
                // execution time constraints. therefore we'll need to defer push notification request submission until the 
                // user foregrounds the app again and the health test submits the requests. the user will be encouraged to
                // do so as they'll begin getting notifications from the local callback invocation loop. in the check below
                // we use BackgroundTimeRemaining rather than ApplicationState, as we're unsure what the state will be when
                // the app is activated by a push notification. we're certain that background time will be limited. we're 
                // using a finite, relatively large value for the background time threshold to capture "in the background".
                // practical values are either the maximum floating point value (for foreground) and less than 30 seconds 
                // (for background).
                if (Protocol.State == ProtocolState.Starting && UIKit.UIApplication.SharedApplication.BackgroundTimeRemaining < 1000)
                {
                    throw new Exception("Starting protocol from the background. Deferring submission of push notification requests.");
                }
#endif

                s3 = await CreateS3ClientAsync();
                byte[] requestJsonBytes = Encoding.UTF8.GetBytes(request.JSON.ToString(Formatting.None));
                MemoryStream dataStream = new MemoryStream(requestJsonBytes);

                await PutAsync(s3, dataStream, GetPushNotificationRequestKey(request.BackendKey), "application/json", cancellationToken);
            }
            finally
            {
                DisposeS3(s3);
            }
        }
示例#19
0
        public void ToAlias()
        {
            var service = new PushService
            {
                RequestBuilder = RequestBuilderHelper.Build()
            };

            var random           = new Random();
            var pushNotification = new PushNotificationRequest
            {
                Aliases = new List <string>(new string[] { "1gzod" }),
                Payload = new PushPayload
                {
                    Badge = random.Next(100),
                    Alert = "What's up iPhone",
                }
            };

            var asyncTestHelper = new AsyncTestHelper();

            service.Execute(pushNotification, response => asyncTestHelper.Callback(null), asyncTestHelper.HandleException);
            asyncTestHelper.Wait();
        }
示例#20
0
        public ActionResult <string> SendPushNotification(PushNotificationRequest req)
        {
            var ocPassword = config.GetValue <string>("OCPassword");

            if (ocPassword == req.OcPassword)
            {
                var notificationTitle = req?.Title;
                var notificationBody  = req?.Body;
                if (!string.IsNullOrEmpty(notificationTitle) && !string.IsNullOrEmpty(notificationBody))
                {
                    this.fcmService.SendPushNotification(notificationTitle, notificationBody);
                    return(Ok("Push notification sent succesfully"));
                }
                else
                {
                    return(BadRequest($"Incorrect push notification title: {notificationTitle} or body: {notificationBody}"));
                }
            }
            else
            {
                return(Unauthorized());
            }
        }
    public async Task push_message_notification_Hub()
    {
        NotificationHubRepository repo = new NotificationHubRepository(notificationHubConString);

        //var registration = new MobileDeviceInstallationNotificationHub()
        //{
        //    InstallationId = "instaltestid",
        //    Platform = "gcm",
        //    PushChannel = "testToken",
        //    Tags = new List<string> { "tag1", "tag2" },
        //    Templates = new System.Collections.Generic.Dictionary<string, NotificationPushTemplate>
        //    {
        //        { "genericTemplate", new NotificationPushTemplate(){
        //            Body="{\"data\":{\"message\":\"Notification Hub test notification\"}}"
        //        }
        //        }
        //    }
        //};

        // await repo.RegisterMobileDevice(registration);

        //"{ "genericTemplate":{ "body":"{\"data\":{\"message\":\"$(messageParam)\"}}"}"

        var pushRequest = new PushNotificationRequest()
        {
            Text   = "{\"data\":{\"message\":\"sample test template\"}",
            Action = "sample action",
            Silent = false,
            Tags   = new List <string> {
                "Test"
            }
        };

        await repo.PushNotification(pushRequest);

        //await repo.SendNotification("{\"data\":{\"message\":\"Notification Hub test notification\"}}", "testtag");
    }
    public void Simple()
    {
        var service = new PushService
        {
            RequestBuilder = RequestBuilderHelper.Build()
        };
        var request = new PushNotificationRequest
        {
            DeviceTokens = new List <string>
            {
                "BadToken"
            },
            Payload = new PushPayload
            {
                Alert = "Alert"
            },
        };

        Exception exception = null;

        try
        {
            var asyncTestHelper = new AsyncTestHelper();
            service.Execute(request, respone => asyncTestHelper.Callback(null), asyncTestHelper.HandleException);
            asyncTestHelper.Wait();
        }
        catch (Exception e)
        {
            exception = e;
        }

        var remoteException = exception as RemoteException;

        Assert.IsNotNull(remoteException);
        Assert.AreEqual("{\"error_code\": 40001, \"details\": {\"device_tokens.0.device_token\": [\"device_token contains an invalid device token: BADTOKEN\"]}, \"error\": \"Data validation error\"}", remoteException.Message);
    }
示例#23
0
        /// <summary>
        /// Requests remote invocation for a <see cref="ScheduledCallback"/>, to be delivered in parallel with the
        /// local invocation loop on iOS. Only one of these (the remote or local) will ultimately be allowed to
        /// run -- whichever arrives first.
        /// </summary>
        /// <returns>Task.</returns>
        /// <param name="callback">Callback.</param>
        private async Task RequestRemoteInvocationAsync(ScheduledCallback callback)
        {
            // not all callbacks are associated with a protocol (e.g., the app-level health test). because push notifications are
            // currently tied to the remote data store of the protocol, we don't currently provide PNR support for such callbacks.
            // on race conditions, it might be the case that the system attempts to schedule a duplicate callback. if this happens
            // the duplicate will not be assigned a next execution, and the system will try to unschedule/delete it. skip such
            // callbacks below.
            if (callback.Protocol != null && callback.NextExecution.HasValue)
            {
                try
                {
                    // the request id must differentiate the current device. furthermore, it needs to identify the
                    // request as one for a callback. lastly, it needs to identify the particular callback that it
                    // targets. the id does not include the callback invocation, as any newer requests for the
                    // callback should obsolete older requests.
                    string id = SensusServiceHelper.Get().DeviceId + "." + SENSUS_CALLBACK_KEY + "." + callback.Id;

                    PushNotificationUpdate update = new PushNotificationUpdate
                    {
                        Type    = PushNotificationUpdateType.Callback,
                        Content = JObject.Parse("{" +
                                                "\"callback-id\":" + JsonConvert.ToString(callback.Id) + "," +
                                                "\"invocation-id\":" + JsonConvert.ToString(callback.InvocationId) +
                                                "}")
                    };

                    PushNotificationRequest request = new PushNotificationRequest(id, SensusServiceHelper.Get().DeviceId, callback.Protocol, update, PushNotificationRequest.LocalFormat, callback.NextExecution.Value, callback.PushNotificationBackendKey);

                    await SensusContext.Current.Notifier.SendPushNotificationRequestAsync(request, CancellationToken.None);
                }
                catch (Exception ex)
                {
                    SensusException.Report("Exception while sending push notification request for scheduled callback:  " + ex.Message, ex);
                }
            }
        }
        public async Task SendPushNotification_GIVEN_Invalid_AccessToken_RETURNS_Null(string accessToken)
        {
            // Arrange.
            var settings = Substitute.For <ISettings>();

            settings["PushNotification:Url"] = "https://www.test.com";

            var tokenType = "bearer";
            var pushNotificationRequest = new PushNotificationRequest
            {
                IdNumber = "9009165023080",
                Title    = "Test Title",
                Message  = "Test Message"
            };

            var httpClientOperations    = Substitute.For <IHttpClientOperations>();
            var pushNotificationService = new PushNotificationService(httpClientOperations, settings);

            // Act.
            var actual = await pushNotificationService.SendPushNotification(accessToken, tokenType, pushNotificationRequest, CancellationToken.None);

            // Assert.
            Assert.IsNull(actual);
        }
示例#25
0
        public ProtocolsPage()
        {
            Title = "Your Studies";

            _protocolsList = new ListView(ListViewCachingStrategy.RecycleElement);
            _protocolsList.ItemTemplate = new DataTemplate(typeof(TextCell));
            _protocolsList.ItemTemplate.SetBinding(TextCell.TextProperty, nameof(Protocol.Caption));
            _protocolsList.ItemTemplate.SetBinding(TextCell.DetailProperty, nameof(Protocol.SubCaption));
            _protocolsList.ItemsSource = SensusServiceHelper.Get()?.RegisteredProtocols;
            _protocolsList.ItemTapped += async(o, e) =>
            {
                if (_protocolsList.SelectedItem == null)
                {
                    return;
                }

                Protocol selectedProtocol = _protocolsList.SelectedItem as Protocol;

                #region add protocol actions
                List <string> actions = new List <string>();

                if (selectedProtocol.State == ProtocolState.Running)
                {
                    actions.Add("Stop");

                    if (selectedProtocol.AllowPause)
                    {
                        actions.Add("Pause");
                    }
                }
                else if (selectedProtocol.State == ProtocolState.Stopped)
                {
                    actions.Add("Start");
                }
                else if (selectedProtocol.State == ProtocolState.Paused)
                {
                    actions.Add("Resume");
                }

                if (selectedProtocol.AllowTagging)
                {
                    actions.Add("Tag Data");
                }

                if (selectedProtocol.State == ProtocolState.Stopped && selectedProtocol.AllowParticipantIdReset)
                {
                    actions.Add("Reset ID");
                }

                if (!string.IsNullOrWhiteSpace(selectedProtocol.ContactEmail))
                {
                    actions.Add("Email Study Manager for Help");
                }

                if (selectedProtocol.State == ProtocolState.Running && selectedProtocol.AllowViewStatus)
                {
                    actions.Add("Status");
                }

                if (selectedProtocol.AllowViewData)
                {
                    actions.Add("View Data");
                }

                if (selectedProtocol.State == ProtocolState.Running)
                {
                    if (selectedProtocol.AllowSubmitData)
                    {
                        actions.Add("Submit Data");
                    }

                    if (selectedProtocol.AllowParticipationScanning)
                    {
                        actions.Add("Display Participation");
                    }
                }

                if (selectedProtocol.AllowParticipationScanning && (selectedProtocol.RemoteDataStore?.CanRetrieveWrittenData ?? false))
                {
                    actions.Add("Scan Participation Barcode");
                }

                actions.Add("Edit");

                if (selectedProtocol.AllowCopy)
                {
                    actions.Add("Copy");
                }

                if (selectedProtocol.Shareable)
                {
                    actions.Add("Share Protocol");
                }

                if (selectedProtocol.AllowLocalDataShare && (selectedProtocol.LocalDataStore?.HasDataToShare ?? false))
                {
                    actions.Add("Share Local Data");
                }

                List <Protocol> groupableProtocols = SensusServiceHelper.Get().RegisteredProtocols.Where(registeredProtocol => registeredProtocol != selectedProtocol && registeredProtocol.Groupable && registeredProtocol.GroupedProtocols.Count == 0).ToList();
                if (selectedProtocol.Groupable)
                {
                    if (selectedProtocol.GroupedProtocols.Count == 0 && groupableProtocols.Count > 0)
                    {
                        actions.Add("Group");
                    }
                    else if (selectedProtocol.GroupedProtocols.Count > 0)
                    {
                        actions.Add("Ungroup");
                    }
                }

                if (selectedProtocol.State == ProtocolState.Stopped && selectedProtocol.StartIsScheduled)
                {
                    actions.Remove("Start");
                    actions.Insert(0, "Cancel Scheduled Start");
                }

                if (selectedProtocol.State == ProtocolState.Running && selectedProtocol.AllowTestPushNotification)
                {
                    actions.Add("Request Test Push Notification");
                }

                actions.Add("Delete");
                #endregion

                #region process selected protocol action
                string selectedAction = await DisplayActionSheet(selectedProtocol.Name, "Cancel", null, actions.ToArray());

                // must reset the protocol selection manually
                _protocolsList.SelectedItem = null;

                if (selectedAction == "Start")
                {
                    await selectedProtocol.StartWithUserAgreementAsync();
                }
                else if (selectedAction == "Cancel Scheduled Start")
                {
                    if (await DisplayAlert("Confirm Cancel", "Are you sure you want to cancel " + selectedProtocol.Name + "?", "Yes", "No"))
                    {
                        await selectedProtocol.CancelScheduledStartAsync();
                    }
                }
                else if (selectedAction == "Stop")
                {
                    if (await DisplayAlert("Confirm Stop", "Are you sure you want to stop " + selectedProtocol.Name + "?", "Yes", "No"))
                    {
                        await selectedProtocol.StopAsync();
                    }
                }
                else if (selectedAction == "Pause")
                {
                    await selectedProtocol.PauseAsync();
                }
                else if (selectedAction == "Resume")
                {
                    await selectedProtocol.ResumeAsync();
                }
                else if (selectedAction == "Tag Data")
                {
                    await Navigation.PushAsync(new TaggingPage(selectedProtocol));
                }
                else if (selectedAction == "Reset ID")
                {
                    selectedProtocol.ParticipantId = null;
                    await SensusServiceHelper.Get().FlashNotificationAsync("Your ID has been reset.");
                }
                else if (selectedAction == "Status")
                {
                    List <AnalyticsTrackedEvent> trackedEvents = await selectedProtocol.TestHealthAsync(true, CancellationToken.None);

                    await Navigation.PushAsync(new ViewTextLinesPage("Status", trackedEvents.SelectMany(trackedEvent =>
                    {
                        return(trackedEvent.Properties.Select(propertyValue => trackedEvent.Name + ":  " + propertyValue.Key + "=" + propertyValue.Value));
                    }).ToList()));
                }
                else if (selectedAction == "Email Study Manager for Help")
                {
                    await SensusServiceHelper.Get().SendEmailAsync(selectedProtocol.ContactEmail, "Help with Sensus study:  " + selectedProtocol.Name,
                                                                   "Hello - " + Environment.NewLine +
                                                                   Environment.NewLine +
                                                                   "I am having trouble with a Sensus study. The name of the study is \"" + selectedProtocol.Name + "\"." + Environment.NewLine +
                                                                   Environment.NewLine +
                                                                   "Here is why I am sending this email:  ");
                }
                else if (selectedAction == "View Data")
                {
                    await Navigation.PushAsync(new ProbesViewPage(selectedProtocol));
                }
                else if (selectedAction == "Submit Data")
                {
                    try
                    {
                        if (await selectedProtocol.RemoteDataStore?.WriteLocalDataStoreAsync(CancellationToken.None))
                        {
                            await SensusServiceHelper.Get().FlashNotificationAsync("Data submitted.");
                        }
                        else
                        {
                            throw new Exception("Failed to submit data.");
                        }
                    }
                    catch (Exception ex)
                    {
                        await SensusServiceHelper.Get().FlashNotificationAsync("Error:  " + ex.Message);
                    }
                }
                else if (selectedAction == "Display Participation")
                {
                    CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();

                    // pop up wait screen while we submit the participation reward datum
                    IEnumerable <InputGroup> inputGroups = await SensusServiceHelper.Get().PromptForInputsAsync(
                        null,
                        new InputGroup[] { new InputGroup {
                                               Name = "Please Wait", Inputs = { new LabelOnlyInput("Submitting participation information.", false) }
                                           } },
                        cancellationTokenSource.Token,
                        false,
                        "Cancel",
                        null,
                        null,
                        null,
                        false,
                        async() =>
                    {
                        ParticipationRewardDatum participationRewardDatum = new ParticipationRewardDatum(DateTimeOffset.UtcNow, selectedProtocol.Participation)
                        {
                            ProtocolId    = selectedProtocol.Id,
                            ParticipantId = selectedProtocol.ParticipantId
                        };

                        bool writeFailed = false;
                        try
                        {
                            await selectedProtocol.RemoteDataStore.WriteDatumAsync(participationRewardDatum, cancellationTokenSource.Token);
                        }
                        catch (Exception)
                        {
                            writeFailed = true;
                        }

                        if (writeFailed)
                        {
                            await SensusServiceHelper.Get().FlashNotificationAsync("Failed to submit participation information to remote server. You will not be able to verify your participation at this time.");
                        }

                        // cancel the token to close the input above, but only if the token hasn't already been canceled.
                        if (!cancellationTokenSource.IsCancellationRequested)
                        {
                            cancellationTokenSource.Cancel();
                        }

                        await SensusContext.Current.MainThreadSynchronizer.ExecuteThreadSafe(async() =>
                        {
                            // only show the QR code for the reward datum if the datum was written to the remote data store and if the data store can retrieve it.
                            await Navigation.PushAsync(new ParticipationReportPage(selectedProtocol, participationRewardDatum, !writeFailed && (selectedProtocol.RemoteDataStore?.CanRetrieveWrittenData ?? false)));
                        });
                    });

                    // if the prompt was closed by the user instead of the cancellation token, cancel the token in order
                    // to cancel the remote data store write. if the prompt was closed by the termination of the remote
                    // data store write (i.e., by the canceled token), then don't cancel the token again.
                    if (!cancellationTokenSource.IsCancellationRequested)
                    {
                        cancellationTokenSource.Cancel();
                    }
                }
                else if (selectedAction == "Scan Participation Barcode")
                {
                    try
                    {
                        string barcodeResult = await SensusServiceHelper.Get().ScanQrCodeAsync(QrCodePrefix.SENSUS_PARTICIPATION);

                        if (barcodeResult == null)
                        {
                            return;
                        }

                        await SensusContext.Current.MainThreadSynchronizer.ExecuteThreadSafe(async() =>
                        {
                            CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();

                            // pop up wait screen while we get the participation reward datum
                            IEnumerable <InputGroup> inputGroups = await SensusServiceHelper.Get().PromptForInputsAsync(
                                null,
                                new InputGroup[] { new InputGroup {
                                                       Name = "Please Wait", Inputs = { new LabelOnlyInput("Retrieving participation information.", false) }
                                                   } },
                                cancellationTokenSource.Token,
                                false,
                                "Cancel",
                                null,
                                null,
                                null,
                                false,
                                async() =>
                            {
                                // after the page shows up, attempt to retrieve the participation reward datum.
                                try
                                {
                                    ParticipationRewardDatum participationRewardDatum = await selectedProtocol.RemoteDataStore.GetDatumAsync <ParticipationRewardDatum>(barcodeResult, cancellationTokenSource.Token);

                                    // cancel the token to close the input above, but only if the token hasn't already been canceled by the user.
                                    if (!cancellationTokenSource.IsCancellationRequested)
                                    {
                                        cancellationTokenSource.Cancel();
                                    }

                                    // ensure that the participation datum has not expired
                                    if (participationRewardDatum.Timestamp > DateTimeOffset.UtcNow.AddSeconds(-SensusServiceHelper.PARTICIPATION_VERIFICATION_TIMEOUT_SECONDS))
                                    {
                                        await SensusContext.Current.MainThreadSynchronizer.ExecuteThreadSafe(async() =>
                                        {
                                            await Navigation.PushAsync(new VerifiedParticipationPage(selectedProtocol, participationRewardDatum));
                                        });
                                    }
                                    else
                                    {
                                        await SensusServiceHelper.Get().FlashNotificationAsync("Participation barcode has expired. The participant needs to regenerate the barcode.");
                                    }
                                }
                                catch (Exception)
                                {
                                    await SensusServiceHelper.Get().FlashNotificationAsync("Failed to retrieve participation information.");
                                }
                                finally
                                {
                                    // cancel the token to close the input above, but only if the token hasn't already been canceled by the user. this will be
                                    // used if an exception is thrown while getting the participation reward datum.
                                    if (!cancellationTokenSource.IsCancellationRequested)
                                    {
                                        cancellationTokenSource.Cancel();
                                    }
                                }
                            });

                            // if the prompt was closed by the user instead of the cancellation token, cancel the token in order
                            // to cancel the datum retrieval. if the prompt was closed by the termination of the remote
                            // data store get (i.e., by the canceled token), then don't cancel the token again.
                            if (!cancellationTokenSource.IsCancellationRequested)
                            {
                                cancellationTokenSource.Cancel();
                            }
                        });
                    }
                    catch (Exception ex)
                    {
                        string message = "Failed to scan barcode:  " + ex.Message;
                        SensusServiceHelper.Get().Logger.Log(message, LoggingLevel.Normal, GetType());
                        await SensusServiceHelper.Get().FlashNotificationAsync(message);
                    }
                }
                else if (selectedAction == "Edit")
                {
                    if (await AuthenticateProtocolAsync(selectedProtocol))
                    {
                        await SensusContext.Current.MainThreadSynchronizer.ExecuteThreadSafe(async() =>
                        {
                            ProtocolPage protocolPage = new ProtocolPage(selectedProtocol);
                            await Navigation.PushAsync(protocolPage);
                        });
                    }
                }
                else if (selectedAction == "Copy")
                {
                    // reset the protocol id, as we're creating a new study
                    await selectedProtocol.CopyAsync(true, true);
                }
                else if (selectedAction == "Share Protocol")
                {
                    await selectedProtocol.ShareAsync();
                }
                else if (selectedAction == "Share Local Data")
                {
                    await selectedProtocol.LocalDataStore?.ShareLocalDataAsync();
                }
                else if (selectedAction == "Group")
                {
                    Input input = await SensusServiceHelper.Get().PromptForInputAsync("Group", new ItemPickerPageInput("Select Protocols", groupableProtocols.Cast <object>().ToList(), textBindingPropertyPath: nameof(Protocol.Name))
                    {
                        Multiselect = true
                    }, null, true, "Group", null, null, null, false);

                    if (input == null)
                    {
                        await SensusServiceHelper.Get().FlashNotificationAsync("No protocols grouped.");

                        return;
                    }

                    ItemPickerPageInput itemPickerPageInput = input as ItemPickerPageInput;

                    List <Protocol> selectedProtocols = (itemPickerPageInput.Value as List <object>).Cast <Protocol>().ToList();

                    if (selectedProtocols.Count == 0)
                    {
                        await SensusServiceHelper.Get().FlashNotificationAsync("No protocols grouped.");
                    }
                    else
                    {
                        selectedProtocol.GroupedProtocols.AddRange(selectedProtocols);
                        await SensusServiceHelper.Get().FlashNotificationAsync("Grouped \"" + selectedProtocol.Name + "\" with " + selectedProtocols.Count + " other protocol" + (selectedProtocols.Count == 1 ? "" : "s") + ".");
                    }
                }
                else if (selectedAction == "Ungroup")
                {
                    if (await DisplayAlert("Ungroup " + selectedProtocol.Name + "?", "This protocol is currently grouped with the following other protocols:" + Environment.NewLine + Environment.NewLine + string.Concat(selectedProtocol.GroupedProtocols.Select(protocol => protocol.Name + Environment.NewLine)), "Ungroup", "Cancel"))
                    {
                        selectedProtocol.GroupedProtocols.Clear();
                    }
                }
                else if (selectedAction == "Request Test Push Notification")
                {
                    try
                    {
                        PushNotificationRequest request = new PushNotificationRequest(SensusServiceHelper.Get().DeviceId + ".test", SensusServiceHelper.Get().DeviceId, selectedProtocol, "Test", "Your test push notification has been delivered.", "default", PushNotificationRequest.LocalFormat, DateTimeOffset.UtcNow, Guid.NewGuid());
                        await SensusContext.Current.Notifier.SendPushNotificationRequestAsync(request, CancellationToken.None);
                        await DisplayAlert("Pending", "Your test push notification was sent and is pending delivery. It should come back within 5 minutes.", "OK");
                    }
                    catch (Exception ex)
                    {
                        await DisplayAlert("Error", "Failed to send test push notification:  " + ex.Message, "OK");
                    }
                }
                else if (selectedAction == "Delete")
                {
                    if (await DisplayAlert("Delete " + selectedProtocol.Name + "?", "This action cannot be undone.", "Delete", "Cancel"))
                    {
                        await selectedProtocol.DeleteAsync();
                    }
                }
                #endregion
            };

            Content = _protocolsList;

            #region add toolbar items
            ToolbarItems.Add(new ToolbarItem(null, "plus.png", async() =>
            {
                string action = await DisplayActionSheet("Add Study", "Back", null, new[] { "From QR Code", "From URL", "New" });

                if (action == "New")
                {
                    await Protocol.CreateAsync("New Study");
                }
                else
                {
                    string url = null;

                    if (action == "From QR Code")
                    {
                        url = await SensusServiceHelper.Get().ScanQrCodeAsync(QrCodePrefix.SENSUS_PROTOCOL);
                    }
                    else if (action == "From URL")
                    {
                        Input input = await SensusServiceHelper.Get().PromptForInputAsync("Download Study", new SingleLineTextInput("Study URL:", Keyboard.Url), null, true, null, null, null, null, false);

                        // input might be null (user cancelled), or the value might be null (blank input submitted)
                        url = input?.Value?.ToString();
                    }

                    if (url != null)
                    {
                        Protocol protocol       = null;
                        Exception loadException = null;

                        // handle managed studies...handshake with authentication service.
                        if (url.StartsWith(Protocol.MANAGED_URL_STRING))
                        {
                            ProgressPage loadProgressPage = null;

                            try
                            {
                                Tuple <string, string> baseUrlParticipantId = ParseManagedProtocolURL(url);

                                AuthenticationService authenticationService = new AuthenticationService(baseUrlParticipantId.Item1);

                                // get account and credentials. this can take a while, so show the user something fun to look at.
                                CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
                                loadProgressPage = new ProgressPage("Configuring study. Please wait...", cancellationTokenSource);
                                await loadProgressPage.DisplayAsync(Navigation);

                                await loadProgressPage.SetProgressAsync(0, "creating account");
                                Account account = await authenticationService.CreateAccountAsync(baseUrlParticipantId.Item2);
                                cancellationTokenSource.Token.ThrowIfCancellationRequested();

                                await loadProgressPage.SetProgressAsync(0.3, "getting credentials");
                                AmazonS3Credentials credentials = await authenticationService.GetCredentialsAsync();
                                cancellationTokenSource.Token.ThrowIfCancellationRequested();

                                await loadProgressPage.SetProgressAsync(0.6, "downloading study");
                                protocol = await Protocol.DeserializeAsync(new Uri(credentials.ProtocolURL), true, credentials);
                                await loadProgressPage.SetProgressAsync(1, null);

                                // don't throw for cancellation here as doing so will leave the protocol partially configured. if
                                // the download succeeds, ensure that the properties get set below before throwing any exceptions.
                                protocol.ParticipantId         = account.ParticipantId;
                                protocol.AuthenticationService = authenticationService;

                                // make sure protocol has the id that we expect
                                if (protocol.Id != credentials.ProtocolId)
                                {
                                    throw new Exception("The identifier of the study does not match that of the credentials.");
                                }
                            }
                            catch (Exception ex)
                            {
                                loadException = ex;
                            }
                            finally
                            {
                                // ensure the progress page is closed
                                await(loadProgressPage?.CloseAsync() ?? Task.CompletedTask);
                            }
                        }
                        // handle unmanaged studies...direct download from URL.
                        else
                        {
                            try
                            {
                                protocol = await Protocol.DeserializeAsync(new Uri(url), true);
                            }
                            catch (Exception ex)
                            {
                                loadException = ex;
                            }
                        }

                        // show load exception to user
                        if (loadException != null)
                        {
                            await SensusServiceHelper.Get().FlashNotificationAsync("Failed to get study:  " + loadException.Message);
                            protocol = null;
                        }

                        // start protocol if we have one
                        if (protocol != null)
                        {
                            // save app state to hang on to protocol, authentication information, etc.
                            await SensusServiceHelper.Get().SaveAsync();

                            // show the protocol to the user and start
                            await Protocol.DisplayAndStartAsync(protocol);
                        }
                    }
                }
            }));

            ToolbarItems.Add(new ToolbarItem("ID", null, async() =>
            {
                await DisplayAlert("Device ID", SensusServiceHelper.Get().DeviceId, "Close");
            }, ToolbarItemOrder.Secondary));

            ToolbarItems.Add(new ToolbarItem("Log", null, async() =>
            {
                Logger logger = SensusServiceHelper.Get().Logger as Logger;
                await Navigation.PushAsync(new ViewTextLinesPage("Log", logger.Read(500, true), logger.Clear));
            }, ToolbarItemOrder.Secondary));

#if __ANDROID__
            ToolbarItems.Add(new ToolbarItem("Stop", null, async() =>
            {
                if (await DisplayAlert("Confirm", "Are you sure you want to stop Sensus? This will end your participation in all studies.", "Stop Sensus", "Go Back"))
                {
                    // stop all protocols and then stop the service. stopping the service alone does not stop
                    // the service, as we want to cover the case when the os stops/destroys the service. in this
                    // case we do not want to mark the protocols as stopped, as we'd like them to start back
                    // up when the os (or a push notification) starts the service again.
                    await SensusServiceHelper.Get().StopAsync();

                    global::Android.App.Application.Context.StopService(AndroidSensusService.GetServiceIntent(false));
                }
            }, ToolbarItemOrder.Secondary));
#endif

            ToolbarItems.Add(new ToolbarItem("About", null, async() =>
            {
                await DisplayAlert("About Sensus", "Version:  " + SensusServiceHelper.Get().Version, "OK");
            }, ToolbarItemOrder.Secondary));
            #endregion
        }
示例#26
0
 public override Task SendPushNotificationRequestAsync(PushNotificationRequest request, CancellationToken cancellationToken)
 {
     return(Task.CompletedTask);
 }
示例#27
0
        public async Task <PushNotificationResponse> SendPushNotification(string accessToken, string tokenType, PushNotificationRequest pushNotificationRequest, CancellationToken cancellationToken)
        {
            if (string.IsNullOrWhiteSpace(accessToken))
            {
                // Log Error.
                return(null);
            }

            if (pushNotificationRequest == null)
            {
                // Log Error.
                return(null);
            }

            if (string.IsNullOrWhiteSpace(pushNotificationRequest.IdNumber))
            {
                // Log Error.
                return(null);
            }

            if (string.IsNullOrWhiteSpace(pushNotificationRequest.Title))
            {
                // Log Error.
                return(null);
            }

            var url = _settings["PushNotification:Url"]; // https://drivewithdialstable.retrotest.co.za/api/v1/profile/send/push/for/idnumber

            if (string.IsNullOrWhiteSpace(url))
            {
                // Log Error.
                return(null);
            }

            var headers = new Dictionary <string, string>
            {
                { "Accept-Charset", "UTF-8" },
                { "Accept", "application/json" }
            };

            var authorizationHeader = new AuthenticationHeaderValue(tokenType.Trim(), accessToken);

            var serializedRequest = JsonConvert.SerializeObject(pushNotificationRequest);
            var httpContent       = new StringContent(serializedRequest, Encoding.UTF8, "application/json");

            var responseString = await _httpClientOperations.SendHttpRequestAsync(HttpMethod.Post, authorizationHeader, headers, url, httpContent, cancellationToken);

            if (string.IsNullOrWhiteSpace(responseString))
            {
                // Log Error.
                return(null);
            }

            return(JsonConvert.DeserializeObject <PushNotificationResponse>(responseString));
        }
        public async Task <NotificationResponse> SendAsync(string title, string message, string idNumber, string correlationId, CancellationToken cancellationToken)
        {
            var errorResponse = new NotificationResponse
            {
                StatusCode = HttpStatusCode.BadRequest
            };

            if (string.IsNullOrWhiteSpace(title))
            {
                _logger.LogError((int)LoggingEvents.ValidationFailed, "PushNotificationManager.SendAsync - title is null or empty");
                errorResponse.AdditionalErrorMessage = "Title is null or empty.";
                return(errorResponse);
            }

            if (string.IsNullOrWhiteSpace(message))
            {
                _logger.LogError((int)LoggingEvents.ValidationFailed, "PushNotificationManager.SendAsync - message is null or empty");
                errorResponse.AdditionalErrorMessage = "Message is null or empty.";
                return(errorResponse);
            }

            if (string.IsNullOrWhiteSpace(idNumber))
            {
                _logger.LogError((int)LoggingEvents.ValidationFailed, "PushNotificationManager.SendAsync - idNumber is null or empty");
                errorResponse.AdditionalErrorMessage = "IdNumber is null or empty.";
                return(errorResponse);
            }

            string accessToken;
            string tokenType;

            var latestAccessTokenResult = await _accessTokenClient.GetLatestAccessTokenAsync(cancellationToken);

            if (latestAccessTokenResult != null && latestAccessTokenResult.DateExpires >= DateTime.UtcNow)
            {
                accessToken = latestAccessTokenResult.AccessToken;
                tokenType   = latestAccessTokenResult.TokenType;
            }
            else
            {
                var accessTokenResult = await _pushNotificationClient.GetAccessTokenAsync(cancellationToken);

                if (accessTokenResult == null)
                {
                    _logger.LogError((int)LoggingEvents.GetItem, "PushNotificationManager.SendAsync - _pushNotificationClient.GetAccessTokenAsync returned null");
                    errorResponse.StatusCode             = HttpStatusCode.ServiceUnavailable;
                    errorResponse.AdditionalErrorMessage = "Error getting a WebToken.";
                    return(errorResponse);
                }

                var newAccessToken = new TbAccessToken
                {
                    AccessToken = accessTokenResult.AccessToken,
                    TokenType   = accessTokenResult.TokenType,
                    ExpiresIn   = accessTokenResult.ExpiresIn,
                    DateIssued  = accessTokenResult.Issued,
                    DateExpires = accessTokenResult.Expires
                };

                var addAccessTokenResult = await _accessTokenClient.AddAccessTokenAsync(newAccessToken, cancellationToken);

                if (addAccessTokenResult <= 0)
                {
                    _logger.LogWarning((int)LoggingEvents.InsertItem, "PushNotificationManager.SendAsync - _accessTokenClient.AddAccessTokenAsync returned no results");
                }

                accessToken = accessTokenResult.AccessToken;
                tokenType   = accessTokenResult.TokenType;
            }

            var pushNotificationRequest = new PushNotificationRequest
            {
                IdNumber = idNumber,
                Title    = title,
                Message  = message
            };

            var pushNotificationResult = await _pushNotificationClient.SendPushNotification(accessToken, tokenType, pushNotificationRequest, cancellationToken);

            if (pushNotificationResult == null)
            {
                _logger.LogError((int)LoggingEvents.ExternalCall, "PushNotificationManager.SendAsync - _pushNotificationClient.SendPushNotification returned null", pushNotificationRequest);
                errorResponse.StatusCode             = HttpStatusCode.ServiceUnavailable;
                errorResponse.AdditionalErrorMessage = "Error creating a Push Notification request.";
                return(errorResponse);
            }

            if (pushNotificationResult.Success)
            {
                return(new NotificationResponse
                {
                    StatusCode = HttpStatusCode.Accepted,
                    AdditionalErrorMessage = pushNotificationResult.Message
                });
            }

            errorResponse.AdditionalErrorMessage = pushNotificationResult.Message;
            return(errorResponse);
        }
示例#29
0
 /// <summary>
 /// Sends the push notification request.
 /// </summary>
 /// <returns>The push notification request.</returns>
 /// <param name="request">Request.</param>
 /// <param name="cancellationToken">Cancellation token.</param>
 public abstract Task SendPushNotificationRequestAsync(PushNotificationRequest request, CancellationToken cancellationToken);