0
votes

I apologize if my question is silly, but I am new to WebApi. I have followed a tutorial and published a WebApi to Azure. I also have created a Xamarin Mobile App and all the framework in Azure to be able to send Push Notifications to both Android and iOS. I have a notification hub set up, app service, web service that hosts the web api etc. Testing with Azure using the Push tab to send notifications individually to both ios and android works perfectly.

I posted the code of the web api. How can I use the web api locally on my computer to send a notification to both platforms (ios and android) please?

[RoutePrefix("sanotifications")]
    public class SANotifController : ApiController
    {


        [HttpPost]
        [Route("")]
        public async Task<IHttpActionResult> SendNotificationAsync ([FromBody] string message)
        {
            //Get the settings for the server project
            HttpConfiguration config = this.Configuration;

            try
            {
                await InternalSendNotificationAsync(message, null);
            }
            catch (Exception ex)
            {
                //write the failure result to the logs
                config.Services.GetTraceWriter().Error(ex.Message, null, "Push.SendAsync Error");
                return BadRequest(ex.Message);
            }

            return Ok();
        }

        [HttpPost]
        [Route("{installationid}")]
        public async Task<IHttpActionResult> SendNotificationAsync(string installationId, [FromBody] string message)
        {
            //get the settings for the server project
            HttpConfiguration config = this.Configuration;

            try
            {
                await SendNotificationAsync(message, installationId);
            }
            catch (Exception ex)
            {
                //write the failure to the logs
                config.Services.GetTraceWriter().Error(ex.Message, null, "Push.SendAsync Error");
                return BadRequest(ex.Message);
            }

            return Ok();
        }



        async Task<NotificationOutcome> InternalSendNotificationAsync (string message, string installationId)
        {
            //Get the settings for the server project
            HttpConfiguration config = this.Configuration;

            //use code below if web api is already published to Azure to get existing setup
            //does not work locally
            var settings = config.GetMobileAppSettingsProvider().GetMobileAppSettings();

            /*
            //Get the Notification Hubs credentials for the Mobile App
            string notificationHubName = settings.NotificationHubName;
            string notificationHubConnection = settings.Connections[MobileAppSettingsKeys.NotificationHubConnectionString].ConnectionString;
            */

            //the name of the Notification Hub from the overview page.
            // works locally
            string notificationHubName = "sa1hub";

            //use "DefaultFullSharedAccessSignature" from the portal's Access Policies
            string notificationHubConnection = "Endpoint=sb://sahub.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=71S2@QEWF#@$";


            // create a new notification hub client
            var hub = NotificationHubClient.CreateClientFromConnectionString(
                notificationHubConnection,
                notificationHubName,
                // Don't use this in RELEASE builds. The number of devices is limited.
                // If TRUE, the send method will return the devices a message was 
                // delivered to.
                enableTestSend: true);

            // use a template compatible with both devices
            // send the message so that all template registrations that contain "messageParam"
            // will receive the notification. This includes APNS, GCM, WNS and MPNS template registrations.
            var templateParams = new Dictionary<string, string>
            {
                ["messageParam"] = message
            };

            // send the push notification and log the results

            NotificationOutcome result = null; 
            if (string.IsNullOrWhiteSpace(installationId))
            {
                result = await hub.SendTemplateNotificationAsync(templateParams).ConfigureAwait(false);
            }
            else
            {
                result = await hub.SendTemplateNotificationAsync(templateParams, "$InstallationId:{" + installationId + "}").ConfigureAwait(false);
            }

            // Write the success result to the logs.
            config.Services.GetTraceWriter().Info(result.State.ToString());
            return result;
        }


    }
}
2

2 Answers

2
votes

In Xamarin there are two way to send push notification from server to client. Even on Microsoft forum it's very clear step mention to Implementation.

  1. Use of Azure Hub notification we can send easily notification on Cross mobile Platform or Native

Azure Push Notification

  1. Another App Center Push notification Implementation.

    Xamarin App Center Push Notification

1
votes

To send push notification for IOS devices you have to communicate with APNS and for Android we need GCM. Azure works like an intermediate between our app and these services. So if you would like to send notification without Azure I prefer Firebase Cloud Messaging. it is google product and allows us to send cross platform push notifications for both IOS and Android.

We can host our WebAPI in our windows local IIS and which should be configured for Firebase.

Example app for xamarin : FirebasePushNotificationPlugin