public async Task ShouldSendPushNotificationAsync_AccountIdsTarget_Success()
        {
            // Arrange
            var loggerMock = new Mock <ILogger>();

            var httpClientMock = new HttpClientMock();

            httpClientMock.SetupSendAsync()
            .ReturnsAsync(HttpResponseMessages.AppCenterPushResponses.Success("notification_id_test"))
            .Verifiable();

            var appCenterConfiguration  = new TestAppCenterConfiguration();
            var pushNotificationService = new AppCenterPushNotificationService(loggerMock.Object, httpClientMock.Object, appCenterConfiguration);

            var appCenterPushMessage = new AppCenterPushMessage
            {
                Content = new AppCenterPushContent
                {
                    Name       = $"AppCenterPushAccountIdsTarget_{Guid.NewGuid():B}",
                    Title      = "Push From App Center",
                    Body       = "Hello! Isn't this an amazing notification message?",
                    CustomData = new Dictionary <string, string> {
                        { "key", "value" }
                    }
                },
                Target = new AppCenterPushAccountIdsTarget
                {
                    AccountIds = new List <string>
                    {
                        "A1DF0327-3945-4B24-B22C-CC34367BEFE3",
                        "DF2D5140-CF24-4921-9045-9FE963112981",
                        "7A3E97D4-3BDA-4DFB-89CD-4C46AAEFF548",
                    }
                }
            };

            // Act
            var responseDtos = await pushNotificationService.SendPushNotificationAsync(appCenterPushMessage);

            // Assert
            responseDtos.Should().HaveCount(2);
            responseDtos.Should().AllBeOfType <AppCenterPushSuccess>();
            var appCenterPushResponse = responseDtos.ElementAt(0) as AppCenterPushSuccess;

            appCenterPushResponse.RuntimePlatform.Should().Be(RuntimePlatform.Android);
            appCenterPushResponse.NotificationId.Should().Be("notification_id_test");

            httpClientMock.VerifySendAsync(
                request => request.Method == HttpMethod.Post &&
                request.RequestUri == new Uri("https://appcenter.ms/api/v0.1/apps/testOrg/TestApp.Android/push/notifications"),
                Times.Exactly(1)
                );
            httpClientMock.VerifySendAsync(
                request => request.Method == HttpMethod.Post &&
                request.RequestUri == new Uri("https://appcenter.ms/api/v0.1/apps/testOrg/TestApp.iOS/push/notifications"),
                Times.Exactly(1)
                );
        }
        public async Task ShouldSendPushNotificationAsync_UserIdsTarget_Success()
        {
            // Arrange
            var loggerMock = new Mock <ILogger>();

            var httpClientMock = new HttpClientMock();

            httpClientMock.SetupSendAsync()
            .ReturnsAsync(HttpResponseMessages.AppCenterPushResponses.Success("notification_id_test"))
            .Verifiable();

            var appCenterConfiguration  = new TestAppCenterConfiguration();
            var pushNotificationService = new AppCenterPushNotificationService(loggerMock.Object, httpClientMock.Object, appCenterConfiguration);

            var appCenterPushMessage = new AppCenterPushMessage
            {
                Content = new AppCenterPushContent
                {
                    Name       = $"AppCenterPushUserIdsTarget_{Guid.NewGuid():B}",
                    Title      = "Push From App Center",
                    Body       = "Hello! Isn't this an amazing notification message?",
                    CustomData = new Dictionary <string, string> {
                        { "key", "value" }
                    }
                },
                Target = new AppCenterPushUserIdsTarget
                {
                    UserIds = new List <string>
                    {
                        "a0061b36-8a50-4e2e-aaab-1c5849dccf30",
                        "91145edf-53ce-4f74-8ebd-8934f08905f6",
                        "7ee7354a-f69a-4a79-929a-b50b66a05518",
                    }
                }
            };

            // Act
            var responseDtos = await pushNotificationService.SendPushNotificationAsync(appCenterPushMessage);

            // Assert
            responseDtos.Should().HaveCount(2);
            responseDtos.Should().AllBeOfType <AppCenterPushSuccess>();
            var appCenterPushResponse = responseDtos.ElementAt(0) as AppCenterPushSuccess;

            appCenterPushResponse.RuntimePlatform.Should().Be(RuntimePlatform.Android);
            appCenterPushResponse.NotificationId.Should().Be("notification_id_test");

            httpClientMock.VerifySendAsync(
                request => request.Method == HttpMethod.Post &&
                request.RequestUri == new Uri("https://appcenter.ms/api/v0.1/apps/testOrg/TestApp.Android/push/notifications"),
                Times.Exactly(1)
                );
            httpClientMock.VerifySendAsync(
                request => request.Method == HttpMethod.Post &&
                request.RequestUri == new Uri("https://appcenter.ms/api/v0.1/apps/testOrg/TestApp.iOS/push/notifications"),
                Times.Exactly(1)
                );
        }
コード例 #3
0
        /// <summary>
        ///     Sends <paramref name="appCenterPushMessage" /> to AppCenter API
        ///     /v0.1​/apps​/{owner_name}​/{app_name}​/push​/notifications
        /// </summary>
        /// <param name="appCenterPushMessage"></param>
        /// <returns>
        ///     Returns a <seealso cref="AppCenterPushResponse" /> for each target runtime platform.
        ///     This can either be <seealso cref="AppCenterPushSuccess" /> or <seealso cref="AppCenterPushError" />.
        /// </returns>
        public async Task <IEnumerable <AppCenterPushResponse> > SendPushNotificationAsync(AppCenterPushMessage appCenterPushMessage)
        {
            if (appCenterPushMessage == null)
            {
                throw new ArgumentNullException(nameof(appCenterPushMessage));
            }

            this.logger.Log(LogLevel.Debug, "SendPushNotificationAsync");
            var pushResponses = new List <AppCenterPushResponse>();

            var organizationName = this.appCenterConfiguration.OrganizationName;
            var appNames         = this.appCenterConfiguration.AppNames;

            foreach (var appNameMappings in appNames)
            {
                AppCenterPushResponse appCenterPushResponse;
                try
                {
                    var appName    = appNameMappings.Value;
                    var requestUri = $"https://appcenter.ms/api/v0.1/apps/{organizationName}/{appName}/push/notifications";
                    this.logger.Log(LogLevel.Debug, $"SendPushNotificationAsync with requestUri={requestUri}");

                    var serialized  = JsonConvert.SerializeObject(appCenterPushMessage, this.jsonSerializerSettings);
                    var httpContent = new StringContent(serialized, Encoding.UTF8, "application/json");

                    var httpResponseMessage = await this.httpClient.PostAsync(requestUri, httpContent);

                    var jsonResponse = await httpResponseMessage.Content.ReadAsStringAsync();

                    if (httpResponseMessage.IsSuccessStatusCode)
                    {
                        appCenterPushResponse = JsonConvert.DeserializeObject <AppCenterPushSuccess>(jsonResponse, this.jsonSerializerSettings);
                    }
                    else
                    {
                        appCenterPushResponse = JsonConvert.DeserializeObject <AppCenterPushError>(jsonResponse, this.jsonSerializerSettings);
                    }
                }
                catch (Exception ex)
                {
                    var errorMessage = $"Failed to send push notification request to app center: {ex.Message}";
                    this.logger.Log(LogLevel.Error, errorMessage);

                    appCenterPushResponse = new AppCenterPushError
                    {
                        ErrorMessage = errorMessage,
                        ErrorCode    = "-1"
                    };
                }

                appCenterPushResponse.RuntimePlatform = appNameMappings.Key;
                pushResponses.Add(appCenterPushResponse);
            }

            return(pushResponses);
        }
コード例 #4
0
        private static async Task SendPushNotificationAsync(IAppCenterConfiguration appCenterConfiguration, List <string> userIds)
        {
            var dateTimeNow = DateTime.Now;

            var appCenterPushNotificationService = new AppCenterPushNotificationService(new ConsoleLogger(), new HttpClient(), appCenterConfiguration);

            var pushMessage = new AppCenterPushMessage
            {
                Content = new AppCenterPushContent
                {
                    Name       = $"AppCenterPushUserIdsTarget_{dateTimeNow:yyyyMMdd_HHmmss}",
                    Title      = "AppCenterPushUserIdsTarget",
                    Body       = $"This message has been sent at {dateTimeNow:G}",
                    CustomData = new Dictionary <string, string> {
                        { "key", "value" }
                    }
                },
                Target = new AppCenterPushUserIdsTarget
                {
                    UserIds = userIds
                }
            };

            var appCenterPushResponses = await appCenterPushNotificationService.SendPushNotificationAsync(pushMessage);

            if (appCenterPushResponses.Any())
            {
                System.Console.WriteLine("");
                System.Console.WriteLine("SendPushNotificationAsync responses:");
                System.Console.WriteLine("------------------------------------");
                foreach (var appCenterPushResponse in appCenterPushResponses)
                {
                    if (appCenterPushResponse is AppCenterPushSuccess success)
                    {
                        System.Console.ForegroundColor = ConsoleColor.Green;
                        System.Console.WriteLine($"--> {appCenterConfiguration.AppNames[success.RuntimePlatform]}: {success.NotificationId}");
                        System.Console.ForegroundColor = ConsoleColor.Gray;
                    }
                    else if (appCenterPushResponse is AppCenterPushError error)
                    {
                        System.Console.ForegroundColor = ConsoleColor.Red;
                        System.Console.WriteLine($"--> {appCenterConfiguration.AppNames[error.RuntimePlatform]}: Code={error.ErrorCode}, Message={error.ErrorMessage}");
                        System.Console.ForegroundColor = ConsoleColor.Gray;
                    }
                }
            }
            else
            {
                System.Console.WriteLine("");
                System.Console.WriteLine("No responses from AppCenter.");
            }

            System.Console.WriteLine("");
            System.Console.WriteLine("GetPushNotificationsAsync:");
            System.Console.WriteLine("--------------------------");
            System.Console.WriteLine("");
            var notificationOverviewResults = await appCenterPushNotificationService.GetPushNotificationsAsync();

            if (notificationOverviewResults.Any())
            {
                System.Console.WriteLine($"NotificationId\t\t\t\t\t| State\t\t| Success\t| Failure");
                foreach (var result in notificationOverviewResults)
                {
                    System.Console.WriteLine($"{result.NotificationId}\t| {result.State}\t| {result.PnsSendSuccess}\t\t| {result.PnsSendFailure}");
                }
            }
            else
            {
                System.Console.WriteLine("");
                System.Console.WriteLine("No responses from AppCenter.");
            }

            System.Console.ReadKey();
        }