示例#1
0
        public static async void SendNotification(string message, List <NotificationType> types)
        {
            NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString(Setting.HUB_Path, Setting.HUB_Name);

            foreach (var t in types)
            {
                var notification =
                    NotificationMessage.SetNotification(t, message);

                switch (t)
                {
                case NotificationType.FCM:
                    await hub.SendFcmNativeNotificationAsync(notification);

                    break;

                case NotificationType.WND:
                    await hub.SendWindowsNativeNotificationAsync(notification);

                    break;

                default:
                    await hub.SendFcmNativeNotificationAsync(notification);

                    break;
                }
            }
        }
        private Task SendPlatformNotificationsAsync(string androidPayload, string iOSPayload, CancellationToken token)
        {
            var sendTasks = new Task[]
            {
                _hub.SendFcmNativeNotificationAsync(androidPayload, token)
            };

            return(Task.WhenAll(sendTasks));
        }
示例#3
0
        Task SendPlatformNotificationsAsync(string androidPayload, string iOSPayload)
        {
            var sendTasks = new Task[]
            {
                _hub.SendFcmNativeNotificationAsync(androidPayload),
                _hub.SendAppleNativeNotificationAsync(iOSPayload)
            };

            return(Task.WhenAll(sendTasks));
        }
示例#4
0
        public async Task <bool> SendToAll(Notification notification, NotificationContext context)
        {
            var finalResult = true;

            try
            {
                var payload =
                    $@"<toast><visual><binding template=""ToastText01""><text id=""1"">{notification.NotificationType.Name}</text></binding></visual></toast>";
                var result = await _hub.SendFcmNativeNotificationAsync(payload);

                if (result.State == NotificationOutcomeState.Abandoned || result.State == NotificationOutcomeState.Unknown)
                {
                    finalResult = false;
                }
            }
            catch (Exception exception)
            {
                _logger.LogError(
                    $"Error sending Android notification with Error: ${exception.Message}");

                finalResult = false;
            }

            try
            {
                var payload = $"{{\"aps\":{{\"alert\":\": {notification.NotificationType.Name}\"}}}}";
                var result  = await _hub.SendAppleNativeNotificationAsync(payload);

                if (result.State == NotificationOutcomeState.Abandoned || result.State == NotificationOutcomeState.Unknown)
                {
                    finalResult = false;
                }
            }
            catch (Exception exception)
            {
                _logger.LogError(
                    $"Error sending iOS notification with Error: ${exception.Message}");
                finalResult = false;
            }

            var relevantSubscriptions = context.Subscriptions.Where(s => s.MineSiteId == notification.MineSiteId).ToList();
            var webResultTasks        = relevantSubscriptions
                                        .Select(async subscription => await SendToSubscription(notification, subscription));

            var webResults = await Task.WhenAll(webResultTasks);

            if (!webResults.All(webRes => webRes))
            {
                finalResult = false;
            }

            return(finalResult);
        }
示例#5
0
        public async Task <HubResponse <NotificationOutcome> > SendNotification(Notification newNotification)
        {
            try
            {
                NotificationOutcome outcome = null;

                switch (newNotification.Platform)
                {
                case MobilePlatform.ApplePushNotificationsService:
                    if (newNotification.Tags == null)
                    {
                        outcome = await _hubClient.SendAppleNativeNotificationAsync(newNotification.Content);
                    }
                    else
                    {
                        outcome = await _hubClient.SendAppleNativeNotificationAsync(newNotification.Content, newNotification.Tags);
                    }
                    break;

                case MobilePlatform.GoogleCloudMessaging:
                    if (newNotification.Tags == null)
                    {
                        outcome = await _hubClient.SendFcmNativeNotificationAsync(newNotification.Content);
                    }
                    else
                    {
                        outcome = await _hubClient.SendFcmNativeNotificationAsync(newNotification.Content, newNotification.Tags);
                    }
                    break;
                }

                if (outcome != null)
                {
                    if (!((outcome.State == NotificationOutcomeState.Abandoned) ||
                          (outcome.State == NotificationOutcomeState.Unknown)))
                    {
                        return(new HubResponse <NotificationOutcome>());
                    }
                }

                return(new HubResponse <NotificationOutcome>().SetAsFailureResponse().AddErrorMessage("Notification was not sent due to issue. Please send again."));
            }

            catch (MessagingException ex)
            {
                return(new HubResponse <NotificationOutcome>().SetAsFailureResponse().AddErrorMessage(ex.Message));
            }

            catch (ArgumentException ex)
            {
                return(new HubResponse <NotificationOutcome>().SetAsFailureResponse().AddErrorMessage(ex.Message));
            }
        }
示例#6
0
        public List <NotificationResponse> SendNotification(NotificationRequest request)
        {
            List <NotificationResponse> response = new List <NotificationResponse>();

            if (request.Types != null)
            {
                foreach (var type in request.Types)
                {
                    NotificationOutcome send = new NotificationOutcome();

                    string notification =
                        NotificationMessage.SetNotification(type, request.Message, request.WindowsNotificationId);

                    Exception e = null;

                    try
                    {
                        switch (type)
                        {
                        case NotificationType.FCM:
                            send = _hub.SendFcmNativeNotificationAsync(notification).Result;
                            break;

                        case NotificationType.WND:
                            send = _hub.SendWindowsNativeNotificationAsync(notification).Result;
                            break;

                        default:
                            send = _hub.SendFcmNativeNotificationAsync(notification).Result;
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        e = ex;

                        continue;
                    }
                    finally
                    {
                        response.Add(new NotificationResponse
                        {
                            Type    = type,
                            Success = (e == null),
                            Error   = e?.Message
                        });
                    }
                }
            }


            return(response);
        }
        public async Task SendBroadcastNotification(Message broadcastMessage)
        {
            Session senderSession = _userHandler.GetUserSession(broadcastMessage.Sender);

            if (senderSession != null)  //  Though sender session is very unlikely to be null
            {
                string jsonPayload = string.Format(_formatString, broadcastMessage.Sender, broadcastMessage.Payload);
                // TagExpression of "not USER_TAG", meaning sending to everyone but USER_TAG
                string targetTagExpression = string.Format("! {0}", _userHandler.GetUserSession(broadcastMessage.Sender).DeviceUuid);

                _logger.LogInformation("Send broadcast notification from {0}", broadcastMessage.Sender);
                await _notificationHubClient.SendFcmNativeNotificationAsync(jsonPayload, targetTagExpression);
            }
        }
示例#8
0
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            string   requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic  data        = JsonConvert.DeserializeObject(requestBody);
            string   post_author = data?.post.post_author;
            string   post_title  = data?.post.post_title;
            DateTime now         = DateTime.Now;

            string title      = $"{post_author} ha creado un nuevo post";
            string body       = post_title;
            string badgeValue = "1";

            // Define the notification hub.
            NotificationHubClient hub =
                NotificationHubClient.CreateClientFromConnectionString(
                    "Endpoint=sb://folderapp.servicebus.windows.net/;SharedAccessKeyName=DefaultFullSharedAccessSignature;SharedAccessKey=EDydYsB/T3zVlJXKmd4LA2c1jWOX15lhl5eRapWa0Zw=",
                    "FolderApp-Xamarin");

            // Define an iOS alert
            var iOSalert =
                "{\"aps\":{\"alert\":\"" + body + "\", \"badge\":" + badgeValue + ", \"sound\":\"default\"},"
                + "\"inAppMessage\":\"" + body + "\"}";

            hub.SendAppleNativeNotificationAsync(iOSalert).Wait();

            // Define an Anroid alert.

            var androidAlert = "{\"data\":{\"title\": \"" + title + "\",\"body\":\"" + body + "\"}}";

            hub.SendFcmNativeNotificationAsync(androidAlert).Wait();

            return(new HttpResponseMessage(HttpStatusCode.OK));
        }
示例#9
0
        private static async Task SendTemplateNotificationsAsync()
        {
            NotificationHubClient       hub = NotificationHubClient.CreateClientFromConnectionString(DispatcherConstants.FullAccessConnectionString, DispatcherConstants.NotificationHubName);
            Dictionary <string, string> templateParameters = new Dictionary <string, string>();

            messageCount++;

            // Send a template notification to each tag. This will go to any devices that
            // have subscribed to this tag with a template that includes "messageParam"
            // as a parameter
            foreach (var tag in DispatcherConstants.SubscriptionTags)
            {
                try
                {
                    var messageAndroid = JsonConvert.SerializeObject(new PayloadAndroid(new Data("Message Title", "Message Body")));
                    await hub.SendFcmNativeNotificationAsync(messageAndroid, tag);

                    var messageiOS = JsonConvert.SerializeObject(new PayloadIOS(new Aps(new Alert("Message Title", "Message Body"))));
                    await hub.SendAppleNativeNotificationAsync(messageiOS, tag);


                    Console.WriteLine($"Sent message to {tag} subscribers.");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Failed to send template notification: {ex.Message}");
                }
            }

            Console.WriteLine($"Sent messages to {DispatcherConstants.SubscriptionTags.Length} tags.");
            WriteSeparator();
        }
        public async Task <IActionResult> Send(NotificationRequest request)
        {
            if (request.Message is SimpleNotificationMessage simpleMessage)
            {
                foreach (var message in simpleMessage.GetPlatformMessages())
                {
                    switch (message.Item1)
                    {
                    case "wns":
                        await _hub.SendWindowsNativeNotificationAsync(message.Item2,
                                                                      $"username:{request.Destination}");

                        break;

                    case "aps":
                        await _hub.SendAppleNativeNotificationAsync(message.Item2,
                                                                    $"username:{request.Destination}");

                        break;

                    case "fcm":
                        await _hub.SendFcmNativeNotificationAsync(message.Item2,
                                                                  $"username:{request.Destination}");

                        break;;
                    }
                }
            }
            else if (request.Message is TemplateNotificationMessage templateMessage)
            {
                await _hub.SendTemplateNotificationAsync(templateMessage.Parameters, $"username:{request.Destination}");
            }

            return(Ok());
        }
        /// <summary>
        ///     Sends a <see cref="ScheduledNotification"/> to a specified user.
        /// </summary>
        /// <param name="pushDetails">Details on how to reach the user.</param>
        /// <param name="notification">The notification object.</param>
        public async Task SendNotificationAsync(UserPushNotificationDetails pushDetails, SwabbrNotification notification)
        {
            if (pushDetails is null)
            {
                throw new ArgumentNullException(nameof(pushDetails));
            }

            switch (pushDetails.PushNotificationPlatform)
            {
            case PushNotificationPlatform.APNS:
                var objApns  = NotificationJsonExtractor.Extract(PushNotificationPlatform.APNS, notification);
                var jsonApns = JsonConvert.SerializeObject(objApns, jsonSettings);
                await _hubClient.SendAppleNativeNotificationAsync(jsonApns, pushDetails.UserId.ToString());

                return;

            case PushNotificationPlatform.FCM:
                var objFcm  = NotificationJsonExtractor.Extract(PushNotificationPlatform.FCM, notification);
                var jsonFcm = JsonConvert.SerializeObject(objFcm, jsonSettings);
                await _hubClient.SendFcmNativeNotificationAsync(jsonFcm, pushDetails.UserId.ToString());

                return;

            default:
                throw new InvalidOperationException(nameof(pushDetails.PushNotificationPlatform));
            }
        }
示例#12
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation($"C# HTTP trigger function");

            string subscriptionKey = Environment.GetEnvironmentVariable("COMPUTER_VISION_SUBSCRIPTION_KEY");
            string endpoint        = Environment.GetEnvironmentVariable("COMPUTER_VISION_ENDPOINT");

            ComputerVisionClient client = Authenticate(endpoint, subscriptionKey);

            var imageDetails = await AnalyzeImageUrl(client, req.Body);

            var giftDeliveryResult = new GiftDeliveryResult(
                imageDetails.Description.Tags.Contains("box"),
                imageDetails.Description.Tags.Contains("gift wrapping"),
                imageDetails.Description.Tags.Contains("ribbon"),
                imageDetails.Description.Tags.Contains("present")
                );

            if (giftDeliveryResult.IsDelivered)
            {
                NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString(
                    Environment.GetEnvironmentVariable("NOTIFICATION_HUB_CONNECTION_STRING"),
                    Environment.GetEnvironmentVariable("NOTIFICATION_HUB_NAME"));

                string payload = "{\"data\": {\"message\":\"A new gift has been delivered.\" }}";

                await hub.SendFcmNativeNotificationAsync(payload);
            }

            return(new OkObjectResult("Request completed"));
        }
示例#13
0
        public static async Task <NotificationOutcome> SendNotificationAsync(NotificationHubClient _hub, string notice, string[] tags)
        {
            var ret = await _hub.SendFcmNativeNotificationAsync(notice, tags);

            await LogFeedback(_hub, ret.NotificationId);

            return(ret);
        }
        public async Task <HubResponse <NotificationOutcome> > SendNotification(Notification newNotification)
        {
            try
            {
                NotificationOutcome outcome = null;
                string jsonPayload          =
                    "{" +
                    getQuotedString("data") + ":" +
                    "{" +
                    getQuotedString("title") + ":" + getQuotedString(newNotification.Title) + "," +
                    getQuotedString("content") + ":" + getQuotedString(newNotification.Content) +
                    "}" +
                    "}";
                if (newNotification.Tags == null)
                {
                    outcome = await _hubClient.SendFcmNativeNotificationAsync(jsonPayload);
                }
                else
                {
                    outcome = await _hubClient.SendFcmNativeNotificationAsync(newNotification.Content, newNotification.Tags);
                }

                if (outcome != null)
                {
                    if (!((outcome.State == NotificationOutcomeState.Abandoned) ||
                          (outcome.State == NotificationOutcomeState.Unknown)))
                    {
                        return(new HubResponse <NotificationOutcome>());
                    }
                }

                return(new HubResponse <NotificationOutcome>().SetAsFailureResponse().AddErrorMessage("Notification was not sent due to issue. Please send again."));
            }

            catch (MessagingException ex)
            {
                return(new HubResponse <NotificationOutcome>().SetAsFailureResponse().AddErrorMessage(ex.Message));
            }

            catch (ArgumentException ex)
            {
                return(new HubResponse <NotificationOutcome>().SetAsFailureResponse().AddErrorMessage(ex.Message));
            }
        }
示例#15
0
 public async Task SendMessage(UserDevice device, string message)
 {
     try
     {
         NotificationOutcome outcome = await Hub.SendFcmNativeNotificationAsync(message, device.Registration.Keys.FirstOrDefault());
     }
     catch (Exception e)
     {
     }
 }
示例#16
0
        static async Task TrySendFcmSilentNotification(NotificationHubClient client, ILogger log)
        {
            try
            {
                log.LogInformation("Sending Silent FCM Push Notifications");

                var jsonPayload           = JsonConvert.SerializeObject(new FcmPushNotification());
                var fcmNotificationResult = await client.SendFcmNativeNotificationAsync(jsonPayload).ConfigureAwait(false);

                log.LogInformation("FCM Notifications Sent");
            }
            catch (Exception e)
            {
                log.LogInformation($"FCM Notification Failed\n{e}");
            }
        }
        public static async Task Run([ActivityTrigger] IDurableActivityContext context,
                                     [Table("PendingApprovals", Connection = "AzureWebJobsStorage")] CloudTable destination,
                                     ILogger log)
        {
            log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");

            var approval = context.GetInput <ApprovalTableEntity>();

            log.LogInformation("Saving pending approval to storage");
            var insertOperation = TableOperation.Insert(approval);
            await destination.ExecuteAsync(insertOperation);

            log.LogInformation("Sending notification");

            var connectionString = Environment.GetEnvironmentVariable("NotificationHubConnectionString", EnvironmentVariableTarget.Process);
            var hub = new NotificationHubClient(connectionString, "rfc-activity");

            var notification = new FcmPayload
            {
                Payload = new FcmPayload.Notification
                {
                    Title       = "Awaiting Approval",
                    Message     = "New Activity Image",
                    ClickAction = "http://localhost:3000/",
                    IconUrl     = approval.ImageUrl
                }
            };
            await hub.SendFcmNativeNotificationAsync(JsonConvert.SerializeObject(notification));

            // And also alert on Slack
            var payload = new Payload
            {
                Type     = PayloadType.WeekylActivity,
                Contents = approval
            };

            var secret = Environment.GetEnvironmentVariable("ActivityBotSecret", EnvironmentVariableTarget.Process);

            var client = new ActivityBotProxy(secret);

            client.Broadcast(payload).Wait();
        }
示例#18
0
        public async Task NotifyAsync(string userId, string deviceId)
        {
            try
            {
                NotificationHubClient hub = NotificationHubClient
                                            .CreateClientFromConnectionString(_options.ConnectionString, _options.HubName);

                string json = JsonConvert.SerializeObject(new
                {
                    data = new
                    {
                        fromDeviceId = deviceId
                    }
                });

                await hub.SendFcmNativeNotificationAsync(json, userId);
            }
            catch (Exception ex)
            {
                _logger.LogError($"Exception thrown in AzureHubNotificationService: {ex}");
            }
        }
示例#19
0
        private void SendAndroid(string title, string message, List <string> tags, ILogger logger)
        {
            try
            {
                var random = new Random(DateTime.Now.Millisecond);

                var androidPayload = new AndroidPushNotificationPayload();
                androidPayload.Data = new AndroidPushNotificationData()
                {
                    Title = title,
                    Body  = message,
                    Id    = random.Next(1, 9999),
                };

                string androidPayloadStr = JsonConvert.SerializeObject(androidPayload);
                _hub.SendFcmNativeNotificationAsync(androidPayloadStr, tags).Wait();
            }
            catch (Exception ex)
            {
                logger.LogError(ex.Message);
                //Do Nothing
            }
        }
示例#20
0
        public async Task <IActionResult> send([FromBody] DeliveryReadyEvent deliverReady)
        {
            string[] userTag = new string[1];
            userTag[0] = "rider:" + deliverReady.ryderId;


            Microsoft.Azure.NotificationHubs.NotificationOutcome outcome = null;

            switch (deliverReady.pns.ToLower())
            {
            case "apns":
                // iOS
                var alert = "{\"aps\":{\"alert\":\"New Delivery is ready\"}}";
                outcome = await hub.SendAppleNativeNotificationAsync(alert, userTag);

                break;

            case "fcm":
                // Android
                var notif = "{ \"data\" : {\"message\":\"New Delivery is ready\",\"deliveryId\":\"" + deliverReady.deliveryId + "\"}}";
                outcome = await hub.SendFcmNativeNotificationAsync(notif, userTag);

                break;
            }

            if (outcome != null)
            {
                if (!((outcome.State == Microsoft.Azure.NotificationHubs.NotificationOutcomeState.Abandoned) ||
                      (outcome.State == Microsoft.Azure.NotificationHubs.NotificationOutcomeState.Unknown)))
                {
                    return(BadRequest());
                }
            }

            return(Ok());
        }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string name = req.Query["name"];

            string  requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data        = JsonConvert.DeserializeObject(requestBody);

            name = name ?? data?.name;

            string responseMessage = string.IsNullOrEmpty(name)
                ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
                : $"Hello, {name}. This HTTP triggered function executed successfully.";

            var notificationHubConnectionString = Environment.GetEnvironmentVariable("NotificationHubConnectionString");
            var notificationHubPath             = Environment.GetEnvironmentVariable("NotificationHubPath");

            NotificationHubClient hub =
                NotificationHubClient.CreateClientFromConnectionString(notificationHubConnectionString, notificationHubPath);

            string reqMsg     = req.Query["Message"];
            string defaultMsg = Environment.GetEnvironmentVariable("DefaultNotificationMessage");;
            string message    = string.IsNullOrEmpty(reqMsg) ? defaultMsg : reqMsg;

            string tag = req.Query["RegId"];

            // Define an Anroid alert.
            var androidAlert = "{\"data\":{\"message\": \"" + message + "\"}}";

            hub.SendFcmNativeNotificationAsync(androidAlert, tag).Wait();

            return(new OkObjectResult(responseMessage));
        }
示例#22
0
            public async Task <Unit> Handle(SendPushNotificationCommand request, CancellationToken cancellationToken)
            {
                var payload = JsonSerializer.Serialize(new
                {
                    notification = new
                    {
                        title        = "Test message",
                        body         = request.Text,
                        priority     = "10",
                        sound        = "default",
                        time_to_live = "600"
                    },
                    data = new
                    {
                        title = "Test message",
                        body  = request.Text,
                        url   = "https://example.com"
                    }
                });

                await notificationHubClient.SendFcmNativeNotificationAsync(payload, string.Empty);

                return(await Unit.Task);
            }
示例#23
0
        private async Task ReceiveMessagesFromDeviceAsync(string partition, CancellationToken cancellationToken)
        {
            var eventHubReceiver = eventHubClient.CreateReceiver(PartitionReceiver.DefaultConsumerGroupName, partition, EventPosition.FromEnd());

            while (true)
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    break;
                }
                var eventData = await eventHubReceiver.ReceiveAsync(1);

                if (eventData == null)
                {
                    continue;
                }

                foreach (var d in eventData)
                {
                    var   data = Encoding.UTF8.GetString(d.Body.ToArray());
                    Event ev   = JsonConvert.DeserializeObject <Event>(data);;
                    switch (ev.EventName)
                    {
                    case LockEvent.EventNameConstant:
                        ev = JsonConvert.DeserializeObject <LockEvent>(data);
                        break;

                    case AccessEvent.EventNameConstant:
                        ev = JsonConvert.DeserializeObject <AccessEvent>(data);
                        break;

                    case UnauthorizedAccessEvent.EventNameConstant:
                        ev = JsonConvert.DeserializeObject <UnauthorizedAccessEvent>(data);
                        break;

                    case AlarmEvent.EventNameConstant:
                        ev = JsonConvert.DeserializeObject <AlarmEvent>(data);
                        break;
                    }

                    string deviceId = d.SystemProperties["iothub-connection-device-id"].ToString();

                    var message = $"{deviceId}: {ev.EventName}";

                    var payload = JsonConvert.SerializeObject(new
                    {
                        notification = new
                        {
                            title        = "AccessControl",
                            body         = message,
                            priority     = "10",
                            sound        = "default",
                            time_to_live = "600"
                        },
                        data = new
                        {
                            title = "AccessControl",
                            body  = message,
                            url   = "https://example.com"
                        }
                    });

                    await notificationHubClient.SendFcmNativeNotificationAsync(payload, string.Empty);

                    await hubContext.Clients.All.ReceiveAlarmNotification(new AlarmNotification()
                    {
                        Title = data
                    });

                    Domain.Enums.AccessEvent e = Domain.Enums.AccessEvent.Undefined;

                    if (ev is AccessControl.Messages.Events.LockEvent f)
                    {
                        if (f.LockState == LockState.Locked)
                        {
                            e = Domain.Enums.AccessEvent.Locked;
                        }
                        else
                        {
                            e = Domain.Enums.AccessEvent.Unlocked;
                        }
                    }
                    if (ev is AccessControl.Messages.Events.AlarmEvent g)
                    {
                        if (g.AlarmState == AlarmState.Armed)
                        {
                            e = Domain.Enums.AccessEvent.Armed;
                        }
                        else
                        {
                            e = Domain.Enums.AccessEvent.Disarmed;
                        }
                    }
                    else if (ev is AccessControl.Messages.Events.AccessEvent)
                    {
                        e = Domain.Enums.AccessEvent.Access;
                    }
                    else if (ev is AccessControl.Messages.Events.UnauthorizedAccessEvent)
                    {
                        e = Domain.Enums.AccessEvent.UnauthorizedAccess;
                    }

                    await _accessLogger.LogAsync(null, e, null, string.Empty);
                }
            }
        }
        public async Task <EbNFResponse> Send(EbNFRequest request)
        {
            EbNFResponse resp = new EbNFResponse();

            try
            {
                Console.WriteLine("EbNFRequest Send start");
                Console.WriteLine("PayLoad: " + request.PayLoad + " ;; Tags :" + string.Join(",", request.Tags ?? new List <string>()));
                NotificationOutcome outcome = null;

                switch (request.Platform)
                {
                case PNSPlatforms.WNS:
                    if (request.Tags == null)
                    {
                        outcome = await client.SendWindowsNativeNotificationAsync(request.PayLoad);
                    }
                    else
                    {
                        outcome = await client.SendWindowsNativeNotificationAsync(request.PayLoad, request.Tags);
                    }
                    break;

                case PNSPlatforms.APNS:
                    if (request.Tags == null)
                    {
                        outcome = await client.SendAppleNativeNotificationAsync(request.PayLoad);
                    }
                    else
                    {
                        outcome = await client.SendAppleNativeNotificationAsync(request.PayLoad, request.Tags);
                    }
                    break;

                case PNSPlatforms.GCM:
                    if (request.Tags == null)
                    {
                        outcome = await client.SendFcmNativeNotificationAsync(request.PayLoad);
                    }
                    else
                    {
                        outcome = await client.SendFcmNativeNotificationAsync(request.PayLoad, request.Tags);
                    }
                    break;
                }

                if (outcome != null)
                {
                    Console.WriteLine("State: " + outcome.State);
                    if (outcome.State == NotificationOutcomeState.Abandoned || outcome.State == NotificationOutcomeState.Unknown)
                    {
                        resp.Status  = false;
                        resp.Message = "Failed to send notification. Try again";
                    }
                    else
                    {
                        resp.Status  = true;
                        resp.Message = "Success";
                    }
                }
                else
                {
                    Console.WriteLine("Error at SendNotification mobile: outcome is null");
                }
            }
            catch (MessagingException ex)
            {
                Console.WriteLine("Error at SendNotification mobile");
                Console.WriteLine(ex.Message);
            }
            catch (ArgumentException ex)
            {
                Console.WriteLine("Error at SendNotification mobile");
                Console.WriteLine(ex.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error at SendNotification mobile");
                Console.WriteLine(ex.Message);
            }
            return(resp);
        }
示例#25
0
        private async Task Do(object ev)
        {
            string deviceId = "test";

            var message = $"{deviceId}: {ev.GetType()}";

            var payload = JsonConvert.SerializeObject(new
            {
                notification = new
                {
                    title        = "AccessControl",
                    body         = message,
                    priority     = "10",
                    sound        = "default",
                    time_to_live = "600"
                },
                data = new
                {
                    title = "AccessControl",
                    body  = message,
                    url   = "https://example.com"
                }
            });

            await _notificationHubClient.SendFcmNativeNotificationAsync(payload, string.Empty);

            await _hubContext.Clients.All.ReceiveAlarmNotification(new AlarmNotification()
            {
                Title = JsonConvert.SerializeObject(ev)
            });

            Domain.Enums.AccessEvent e = Domain.Enums.AccessEvent.Undefined;

            if (ev is AccessControl.Contracts.Events.LockEvent f)
            {
                if (f.LockState == LockState.Locked)
                {
                    e = Domain.Enums.AccessEvent.Locked;
                }
                else
                {
                    e = Domain.Enums.AccessEvent.Unlocked;
                }
            }
            if (ev is AccessControl.Contracts.Events.AlarmEvent g)
            {
                if (g.AlarmState == AlarmState.Armed)
                {
                    e = Domain.Enums.AccessEvent.Armed;
                }
                else
                {
                    e = Domain.Enums.AccessEvent.Disarmed;
                }
            }
            else if (ev is AccessControl.Contracts.Events.AccessEvent)
            {
                e = Domain.Enums.AccessEvent.Access;
            }
            else if (ev is AccessControl.Contracts.Events.UnauthorizedAccessEvent)
            {
                e = Domain.Enums.AccessEvent.UnauthorizedAccess;
            }

            await _accessLogger.LogAsync(null, e, null, string.Empty);
        }
示例#26
0
 private static async void SendNotificationAsync()
 {
     NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString("Endpoint=sb://pushcrm.servicebus.windows.net/;SharedAccessKeyName=DefaultFullSharedAccessSignature;SharedAccessKey=KF47Bbxdhz+nnninLfbIEi/VXPPYVKa5ZaMwkO5I6/U=", "Test_notification_hub");
     String message            = "{\"data\":{\"Test message\":\"Доров\"}}";
     await hub.SendFcmNativeNotificationAsync(message);
 }
示例#27
0
 private static async void SendNotificationAsync(string message)
 {
     await hub.SendFcmNativeNotificationAsync("{ \"data\" : {\"Message\":\"" + message + "\"}}");
 }
        public static async void Run([TimerTrigger("0 0 8 * * *")] TimerInfo myTimer, ILogger log)
        {
            log.LogInformation($"C# Prekid rezervacije function executed at: {DateTime.Now}");

            NotificationHubClient hub =
                NotificationHubClient.CreateClientFromConnectionString("Endpoint=sb://foiknjiznicanotificationhub-ns.servicebus.windows.net/;SharedAccessKeyName=DefaultFullSharedAccessSignature;SharedAccessKey=EdMFKv2S17MgtwqY/u57G7capol0MKbGaBZ1VokQRmM=",
                                                                       "FoiKnjiznicaNotificationHub");

            string connString = "Server=tcp:foiknjiznica2.database.windows.net,1433;Initial Catalog=foiknjiznica;Persist Security Info=False;User ID=foi;Password=admin123!;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;";

            List <int> listaIDKopija    = new List <int>();
            List <int> listaIDKorisnika = new List <int>();

            using (SqlConnection conn = new SqlConnection(connString))
            {
                conn.Open();

                var text = $"SELECT kopija_id FROM Kopija_Publikacije";

                using (SqlCommand cmd = new SqlCommand(text, conn))
                {
                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            if (!reader.IsDBNull(0))
                            {
                                listaIDKopija.Add(reader.GetInt32(0));
                            }
                        }
                    }
                }

                foreach (var idKopije in listaIDKopija)
                {
                    var naredba = $"SELECT TOP 1 ClanoviId FROM Stanje_Publikacije WHERE KopijaID = '{idKopije}' AND CONVERT(date,datum_do) = CONVERT(DATE,dateadd(day,-1,GETDATE())) AND Vrsta_StatusaId IN(3) ORDER BY datum DESC";

                    // Za testiranje je potrebno promijeniti dateadd funkciju tako da se doda današnjem danu broj dana za koju rezervaciju treba probati
                    //var naredba = $"SELECT TOP 1 ClanoviId,id FROM Stanje_Publikacije WHERE KopijaID = '{idKopije}' AND CONVERT(date,datum_do) = CONVERT(DATE,dateadd(day,3,GETDATE()))  AND Vrsta_StatusaId IN(3) ORDER BY datum DESC";

                    using (SqlCommand cmd = new SqlCommand(naredba, conn))
                    {
                        using (SqlDataReader reader = cmd.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                if (!reader.IsDBNull(0))
                                {
                                    //log.LogInformation($"Korisnik {reader.GetInt32(0).ToString()} se prekida publikacija {idKopije.ToString()} ");

                                    var httpClient = new HttpClient();
                                    var Json       = JsonConvert.SerializeObject(new PovijestPublikacije()
                                    {
                                        clanoviId = reader.GetInt32(0), kopijaId = idKopije, id = reader.GetInt32(1)
                                    });
                                    var content = new StringContent(Json, Encoding.UTF8, "application/json");
                                    log.LogInformation(Json);
                                    var odgovor = await httpClient.PostAsync("http://foiknjiznica2.azurewebsites.net/api/PrekidRezervacije", content);

                                    listaIDKorisnika.Add(reader.GetInt32(0));
                                }
                            }
                        }
                    }
                }

                foreach (var korisnik in listaIDKorisnika)
                {
                    var naredbaSlanje = $"select mobitelID from Clanovi where id ='{korisnik}'";

                    using (SqlCommand cmd = new SqlCommand(naredbaSlanje, conn))
                    {
                        using (SqlDataReader reader = cmd.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                if (!reader.IsDBNull(0))
                                {
                                    string androidAlert = "{\"data\":{ \"message\":\"Istekla Vam je rezervacija!\"}}";
                                    //log.LogInformation($"Saljem {androidAlert} korisniku {reader.GetString(0)}");
                                    hub.SendFcmNativeNotificationAsync(androidAlert, reader.GetString(0)).Wait();
                                }
                            }
                        }
                    }
                }
            }
        }
 private async void SendNotificationToAndroid(string message, string toUsername)
 {
     string payload = "{ \"data\":{ \"message\":\"" + message + "\"} }";
     await _hub.SendFcmNativeNotificationAsync(payload, toUsername);
 }
示例#30
0
        public async Task <NotificationOutcomeState> SendAndroidNotification(string title, string subTitle, string userId, string eventCode, string type, bool enableCustomSounds, int count, string color, NotificationHubClient hubClient = null)
        {
            try
            {
                if (hubClient == null)
                {
                    hubClient = NotificationHubClient.CreateClientFromConnectionString(Config.ServiceBusConfig.AzureNotificationHub_FullConnectionString, Config.ServiceBusConfig.AzureNotificationHub_PushUrl);
                }

                string androidNotification = null;

                //if (type == ((int)PushSoundTypes.CallEmergency).ToString() ||
                //	type == ((int)PushSoundTypes.CallHigh).ToString() ||
                //	type == ((int)PushSoundTypes.CallMedium).ToString() ||
                //	type == ((int)PushSoundTypes.CallLow).ToString())
                if (eventCode.ToLower().StartsWith("c"))
                {
                    androidNotification = CreateAndroidNotification(title, subTitle, eventCode, type, count, color, "calls");

                    //if (enableCustomSounds && type.Contains("CallPAudio"))
                    //{

                    /*
                     * androidNotification = "{ \"data\" : {\"title\":\"" + title + "\", \"message\":\"" + subTitle +
                     *                                        "\", \"content-available\": \"1\", \"eventCode\":\"" + eventCode + "\", \"sound\":\"" +
                     *                                        FormatForAndroidNativePush(GetSoundFileNameFromType(Platforms.Android, type,
                     *                                                enableCustomSounds)) + "\", \"soundname\":\"" +
                     *                                        FormatForAndroidNativePush(GetSoundFileNameFromType(Platforms.Android, type,
                     *                                                enableCustomSounds)) + "\"," + "}}";
                     */

                    //	androidNotification = CreateAndroidDataNotification(title, subTitle, eventCode, type, count, color);
                    //androidNotification = CreateAndroidNotification(title, subTitle, eventCode, type, count, color);
                    //}
                    //else
                    //{
                    //	androidNotification = "{ \"data\" : {\"title\":\"" + title + "\", \"message\":\"" + subTitle +
                    //						  "\", \"content-available\": \"1\", \"eventCode\":\"" + eventCode + "\", \"sound\":\"" +
                    //						  FormatForAndroidNativePush(GetSoundFileNameFromType(Platforms.Android, type,
                    //							  enableCustomSounds)) + "\", \"soundname\":\"" +
                    //						  FormatForAndroidNativePush(GetSoundFileNameFromType(Platforms.Android, type,
                    //							  enableCustomSounds)) + "\"," +
                    //						  //"\"actions\": [{ title: \"RESPONDING\", callback: \"window.pushActionResponding\"},{ title: \"NOT RESPONDING\", callback: \"window.pushActionNotResponding\"},]" +
                    //						  "\"actions\": [{ icon: \"emailGuests\", title: \"RESPONDING\", callback: \"pushActionResponding\"},{ icon: \"emailGuests\", title: \"NOT RESPONDING\", callback: \"pushActionNotResponding\"}]" +
                    //						  "}}";
                    //}
                }
                else
                {
                    androidNotification = "{ \"data\" : {\"title\":\"" + title + "\", \"message\":\"" + subTitle +
                                          "\", \"eventCode\":\"" + eventCode + "\", \"sound\":\"" +
                                          FormatForAndroidNativePush(GetSoundFileNameFromType(Platforms.Android, type,
                                                                                              enableCustomSounds)) + "\", \"soundname\":\"" +
                                          FormatForAndroidNativePush(GetSoundFileNameFromType(Platforms.Android, type,
                                                                                              enableCustomSounds)) + "\"}}";
                }

                var androidOutcome = await hubClient.SendFcmNativeNotificationAsync(androidNotification, string.Format("userId:{0}", userId));

                return(androidOutcome.State);
            }
            catch (Exception ex)
            {
                string exception = ex.ToString();
            }

            return(NotificationOutcomeState.Unknown);
        }