protected override void RequestStartup(TinyIoCContainer requestContainer, IPipelines pipelines, NancyContext context)
        {
            var path        = context.Request.Path;
            var method      = context.Request.Method;
            var contentType = context.Request.Headers["content-type"].FirstOrDefault();
            var msg         = string.Empty;

            if (path.ToLower().Contains("/requestlog") && method.ToUpper() == "POST")
            {
                var     json    = ReadBody(context.Request.Body);
                dynamic jsonObj = JObject.Parse(json);
                msg = string.Format("Log request for {0} {1}", jsonObj.Method, jsonObj.Path);
            }
            else
            {
                msg = string.Format("{0} {1}", method, path);
            }

            var feedId = context.Request.Headers["X-socketFeedId"].FirstOrDefault() ?? "required Header not set";

            if (feedId.Contains("required Header"))
            {
                _logger.Error("X-socketFeedId not set");
            }

            var socketServerAccesstoken = context.Request.Headers["X-socketServerAccessToken"].FirstOrDefault() ?? "required Header not set";

            if (socketServerAccesstoken.Contains("required Header"))
            {
                _logger.Error("X-socketFeedId not set");
            }

            WebNotification.Send(socketServerAccesstoken, feedId, msg);
        }
        public async Task SendAdminUpdateToUser(WebNotification notification)
        {
            string userEmail    = Context.GetHttpContext().User.FindFirst("email")?.Value ?? "NoUser";
            string userTimeZone = Context.GetHttpContext().User.FindFirst("timezone")?.Value ?? "Romance Standard Time";

            if (userEmail.ToUpper() == Constants.AdminEmail.ToUpper())
            {
                if (notification.To == "OnlineUsers")
                {
                    await Clients.All.SendAsync("ReceiveMessage", JsonConvert.SerializeObject(notification));
                }
                else
                {
                    notification.DateTime = DateTime.UtcNow;
                    await _context.WebNotificationsDb.AddAsync(notification);

                    await _context.SaveChangesAsync();

                    WebNotification webNotification = new WebNotification();
                    webNotification.Title    = "Notification Sent to " + notification.To;
                    webNotification.Message  = "";
                    webNotification.From     = Constants.AppName;
                    webNotification.Type     = "Notification";
                    webNotification.DateTime = DateTime.UtcNow;
                    webNotification.DateTime = TimeZoneInfo.ConvertTimeFromUtc(webNotification.DateTime,
                                                                               TimeZoneInfo.FindSystemTimeZoneById(userTimeZone));
                    webNotification.DateTimeString = webNotification.DateTime.ToString("dd-MMM-yyyy HH:mm");
                    if (String.IsNullOrEmpty(webNotification.Link))
                    {
                        webNotification.Link = "/Notifications?Id=" + webNotification.Id;
                    }
                    await Clients.Caller.SendAsync("ReceiveMessage", JsonConvert.SerializeObject(webNotification));
                }
            }
        }
        public async Task SetUnread(string notification)
        {
            string userId = Context.GetHttpContext().User.FindFirst("sub")?.Value ?? "NoUser";
            int    id;
            bool   idParsed = Int32.TryParse(notification, out id);

            if (idParsed)
            {
                WebNotification updateNotification =
                    await _context.WebNotificationsDb.SingleOrDefaultAsync(n => n.Id == id);

                if (updateNotification != null)
                {
                    if (userId == updateNotification.To)
                    {
                        if (String.IsNullOrEmpty(updateNotification.Link))
                        {
                            updateNotification.Link = "/Notifications?Id=" + updateNotification.Id;
                        }
                        updateNotification.IsRead = false;
                        _context.WebNotificationsDb.Update(updateNotification);
                        await _context.SaveChangesAsync();

                        await Clients.User(userId).SendAsync("UpdateMessage", JsonConvert.SerializeObject(updateNotification));
                    }
                }
            }
        }
Beispiel #4
0
        public IActionResult SendAdminMessage()
        {
            // Todo: Implement Admin as role instead
            WebNotification model = new WebNotification();

            return(View(model));
        }
Beispiel #5
0
        /// <summary>
        /// Update a web notification
        /// </summary>
        /// <param name="domain"></param>
        public void Update(WebNotificationDomain domain)
        {
            WebNotification webNotification = _context.WebNotification.FirstOrDefault(x => x.WebNotificationId == domain.Id);

            webNotification.FromDomainModel(domain);
            _context.SaveChanges();
        }
Beispiel #6
0
        /// <summary>
        /// Get web notification by id
        /// </summary>
        /// <param name="webNotificationId"></param>
        /// <returns></returns>
        public WebNotificationDomain GetById(int webNotificationId)
        {
            WebNotification    webNotification    = _context.WebNotification.FirstOrDefault(x => x.WebNotificationId == webNotificationId);
            NotificationDomain notificationDomain = _context.Notification.FirstOrDefault(x => x.NotificationId == webNotification.NotificationId).ToDomainModel();

            return(webNotification.ToDomainModel(notificationDomain));
        }
        public void SendNotificationOnWeb()
        {
            PushNotification           obj = null;
            AndroidGCMPushNotification objAndroidGCMPushNotification = new AndroidGCMPushNotification();

            try
            {
                DataTable dt = objAndroidGCMPushNotification.GetUserPushNotification("W");
                if (dt != null)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        obj              = new PushNotification();
                        obj.Sno          = Convert.ToInt32(dt.Rows[i]["Sno"]);
                        obj.MessageType  = Convert.ToString(dt.Rows[i]["MessageType"]);
                        obj.MessageText  = Convert.ToString(dt.Rows[i]["MessageText"]);
                        obj.DeviceToken  = Convert.ToString(dt.Rows[i]["DeviceToken"]);
                        obj.MessageTitle = Convert.ToString(dt.Rows[i]["MessageTitle"]);
                        obj.Data         = Convert.ToString(dt.Rows[i]["Data"]);
                        obj.OtherDetails = Convert.ToString(dt.Rows[i]["OtherDetails"]);
                        obj.Data         = obj.Data.Trim() + obj.OtherDetails;
                        string val1 = obj.MessageType + "-" + obj.Data;
                        obj.Data        = obj.MessageText;
                        obj.MessageText = val1;
                        //end here
                        if (!string.IsNullOrEmpty(obj.DeviceToken))
                        {
                            WebNotification obj1 = new WebNotification();
                            obj1.Sno          = Convert.ToInt32(dt.Rows[i]["Sno"]);
                            obj1.MessageType  = Convert.ToString(dt.Rows[i]["MessageType"]);
                            obj1.MessageText  = Convert.ToString(dt.Rows[i]["MessageText"]);
                            obj1.DeviceToken  = Convert.ToString(dt.Rows[i]["DeviceToken"]);
                            obj1.MessageTitle = Convert.ToString(dt.Rows[i]["MessageTitle"]);
                            obj1.Data         = Convert.ToString(dt.Rows[i]["Data"]);
                            obj1.LoginID      = dt.Rows[i]["LoginID"].ToString().Trim();

                            Console.WriteLine("Sending notification on web for message ID: " + obj1.Sno);
                            string         title      = obj.MessageType + "-" + obj.Data;
                            string         url        = WebApiUrl + "GetChallengeNotification?connection=" + obj.DeviceToken + "&msg=" + obj.MessageText + "&title=" + title;
                            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);

                            using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse())
                            {
                                webResponse.Close();
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                obj.Messageid = string.Empty;
                obj.Error     = ex.Message;
                objAndroidGCMPushNotification.UpdateUserPushNotification(obj);
            }
            finally
            {
                obj = null;
            }
        }
 private void Omnilink_OnThermostatStatus(object sender, ThermostatStatusEventArgs e)
 {
     if (!e.EventTimer)
     {
         WebNotification.Send("thermostat", JsonConvert.SerializeObject(e.Thermostat.ToContract()));
     }
 }
        public void Startup()
        {
            WebNotification.RestoreSubscriptions();

            Uri uri = new Uri("http://0.0.0.0:" + Global.webapi_port + "/");

            host = new WebServiceHost(typeof(OmniLinkService), uri);

            try
            {
                ServiceEndpoint ep = host.AddServiceEndpoint(typeof(IOmniLinkService), new WebHttpBinding(), "");
                host.Open();

                log.Info("Listening on " + uri.ToString());
            }
            catch (CommunicationException ex)
            {
                log.Error("An exception occurred starting web service", ex);
                host.Abort();
            }

            // Wait until shutdown
            trigger.WaitOne();

            if (host != null)
            {
                host.Close();
            }

            WebNotification.SaveSubscriptions();
        }
Beispiel #10
0
        public async Task <IActionResult> SendAdminMessage(WebNotification notification)
        {
            // Todo: Implement Admin as role instead
            string userId       = User.FindFirst("sub")?.Value ?? "NoUser";
            string userEmail    = User.FindFirst("email")?.Value ?? "NoUser";
            string userTimeZone = User.FindFirst("timezone")?.Value ?? "NoUser";

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

            if (userEmail.ToUpper() == _adminEmail.ToUpper())
            {
                if (notification.To == "OnlineUsers")
                {
                    notification.DateTime = DateTime.UtcNow;
                    notification.DateTime = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow,
                                                                            TimeZoneInfo.FindSystemTimeZoneById(userTimeZone));
                    notification.DateTimeString = notification.DateTime.ToString("dd-MMM-yyyy HH:mm");
                    await _hubContext.Clients.All.SendAsync("ReceiveMessage", JsonConvert.SerializeObject(notification));
                }
                else
                {
                    UserInfo userinfo;
                    if (notification.To.Contains('@'))
                    {
                        userinfo = await _progenyHttpClient.GetUserInfo(notification.To);

                        notification.To = userinfo.UserId;
                    }
                    else
                    {
                        userinfo = await _progenyHttpClient.GetUserInfoByUserId(notification.To);
                    }

                    notification.DateTime = DateTime.UtcNow;
                    await _context.WebNotificationsDb.AddAsync(notification);

                    await _context.SaveChangesAsync();

                    await _hubContext.Clients.User(userinfo.UserId).SendAsync("ReceiveMessage", JsonConvert.SerializeObject(notification));

                    WebNotification webNotification = new WebNotification();
                    webNotification.Title    = "Notification Sent";
                    webNotification.Message  = "To: " + notification.To + "<br/>From: " + notification.From + "<br/><br/>Message: <br/>" + notification.Message;
                    webNotification.From     = Constants.AppName + " Notification System";
                    webNotification.Type     = "Notification";
                    webNotification.DateTime = DateTime.UtcNow;
                    webNotification.DateTime = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow,
                                                                               TimeZoneInfo.FindSystemTimeZoneById(userinfo.Timezone));
                    webNotification.DateTimeString = webNotification.DateTime.ToString("dd-MMM-yyyy HH:mm");
                    await _hubContext.Clients.User(userId).SendAsync("ReceiveMessage", JsonConvert.SerializeObject(webNotification));
                }
            }

            notification.Title = "Notification Added";
            return(View(notification));
        }
Beispiel #11
0
 public IActionResult ShowUpdatedNotification(WebNotification notification)
 {
     if (!notification.Icon.StartsWith("/") && !notification.Icon.StartsWith("http"))
     {
         notification.Icon = _imageStore.UriFor(notification.Icon, "profiles");
     }
     return(PartialView(notification));
 }
Beispiel #12
0
        /// <summary>
        /// Add a web notification
        /// </summary>
        /// <param name="domain"></param>
        /// <returns></returns>
        public int Add(WebNotificationDomain domain)
        {
            WebNotification webNotification = new WebNotification().FromDomainModel(domain);

            _context.WebNotification.Add(webNotification);
            _context.SaveChanges();
            return(webNotification.WebNotificationId);
        }
 private void Omnilink_OnThermostatStatus(object sender, ThermostatStatusEventArgs e)
 {
     // Ignore events fired by thermostat polling and when temperature is invalid
     // An invalid temperature can occur when a Zigbee thermostat is unreachable
     if (!e.EventTimer && e.Thermostat.Temp > 0)
     {
         WebNotification.Send("thermostat", JsonConvert.SerializeObject(e.Thermostat.ToContract()));
     }
 }
Beispiel #14
0
 /// <summary>
 /// Update multiple web notifications
 /// </summary>
 /// <param name="domains"></param>
 public void Update(ICollection <WebNotificationDomain> domains)
 {
     foreach (WebNotificationDomain domain in domains)
     {
         WebNotification webNotification = _context.WebNotification.FirstOrDefault(x => x.WebNotificationId == domain.Id);
         webNotification.FromDomainModel(domain);
     }
     _context.SaveChanges();
 }
        private void Omnilink_OnZoneStatus(object sender, ZoneStatusEventArgs e)
        {
            if (e.Zone.IsTemperatureZone())
            {
                WebNotification.Send("temp", JsonConvert.SerializeObject(e.Zone.ToContract()));
                return;
            }

            WebNotification.Send(Enum.GetName(typeof(DeviceType), e.Zone.ToDeviceType()), JsonConvert.SerializeObject(e.Zone.ToContract()));
        }
        public async Task ProcessNotificationsAsync_WithValidInputs()
        {
            List <WebNotificationRequestItem> webNotificationRequestItems = new List <WebNotificationRequestItem>
            {
                new WebNotificationRequestItem
                {
                    NotificationId = Guid.NewGuid().ToString(),
                    Title          = "Test Title",
                    Body           = "Test Body",
                    Priority       = NotificationPriority.Normal,
                    Recipient      = new Person {
                        Name = "P1", Email = "*****@*****.**", ObjectIdentifier = Guid.NewGuid().ToString()
                    },
                    PublishOnUTCDate = DateTime.UtcNow.AddDays(1),
                    SendOnUtcDate    = DateTime.UtcNow,
                    ExpiresOnUTCDate = DateTime.UtcNow.AddDays(2),
                    Sender           = new Person {
                        Name = "P2", Email = "*****@*****.**", ObjectIdentifier = Guid.NewGuid().ToString()
                    },
                    TrackingId = Guid.NewGuid().ToString(),
                },
                new WebNotificationRequestItem
                {
                    NotificationId = Guid.NewGuid().ToString(),
                    Title          = "Test Title",
                    Body           = "Test Body",
                    Priority       = NotificationPriority.Normal,
                    Recipient      = new Person {
                        Name = "P1", Email = "*****@*****.**", ObjectIdentifier = Guid.NewGuid().ToString()
                    },
                    PublishOnUTCDate = DateTime.UtcNow.AddDays(-1),
                    SendOnUtcDate    = DateTime.UtcNow,
                    ExpiresOnUTCDate = DateTime.UtcNow.AddDays(2),
                    Sender           = new Person {
                        Name = "P2", Email = "*****@*****.**", ObjectIdentifier = Guid.NewGuid().ToString()
                    },
                    TrackingId = Guid.NewGuid().ToString(),
                },
            };

            EntityCollection <WebNotificationItemEntity> collection = new EntityCollection <WebNotificationItemEntity>();

            collection.Items = webNotificationRequestItems.Select(wbr => wbr.ToEntity(this.ApplicationName)).ToList();
            _ = this.notificationsRepositoryMock.Setup(rp => rp.UpsertAsync(It.IsAny <IEnumerable <WebNotificationItemEntity> >())).ReturnsAsync(collection.Items);
            _ = this.notificationsRepositoryMock.Setup <Task <EntityCollection <WebNotificationItemEntity> > >(rp => rp.ReadAsync(It.IsAny <Expression <Func <WebNotificationItemEntity, bool> > >(), It.IsAny <Expression <Func <WebNotificationItemEntity, NotificationPriority> > >(), It.IsAny <string>(), It.IsAny <int>())).
                Returns(Task.FromResult(collection));
            IEnumerable <WebNotification> notifications = await this.NotificationManager.ProcessNotificationsAsync(this.ApplicationName, webNotificationRequestItems);

            WebNotification notification = notifications.FirstOrDefault();

            Assert.IsTrue(notifications.Count() == 1);
            Assert.IsTrue(notification.NotificationId.Equals(webNotificationRequestItems.Last().NotificationId, StringComparison.Ordinal));
        }
        /// <summary>
        /// Broadcasts the notification asynchronously.
        /// </summary>
        /// <param name="notification">The instance of <see cref="WebNotification"/>.</param>
        /// <returns>The instance of <see cref="Task"/> representing an asynchronous operation.</returns>
        public async Task BroadcastNotificationAsync(WebNotification notification)
        {
            this.logger.LogInformation($"Started {nameof(this.BroadcastNotificationAsync)} method of {nameof(NotificationsHub)}.");
            if (notification == null)
            {
                throw new ArgumentNullException(nameof(notification));
            }

            await this.Clients.All.ReceiveNotificationAsync(notification).ConfigureAwait(false);

            this.logger.LogInformation($"Finished {nameof(this.BroadcastNotificationAsync)} method of {nameof(NotificationsHub)}.");
        }
        public async Task SendUpdateToUser(WebNotification notification)
        {
            string userId       = Context.GetHttpContext().User.FindFirst("sub")?.Value ?? "NoUser";
            string userTimeZone = Context.GetHttpContext().User.FindFirst("timezone")?.Value ?? "Romance Standard Time";

            // Todo: Check if sender has access rights to send to receiver.

            if (userId != "NoUser")
            {
                UserInfo userinfo;
                if (notification.To.Contains('@'))
                {
                    userinfo = await _progenyHttpClient.GetUserInfo(notification.To);

                    notification.To = userinfo.UserId;
                }
                else
                {
                    userinfo = await _progenyHttpClient.GetUserInfoByUserId(notification.To);
                }


                notification.From = userId;
                if (!String.IsNullOrEmpty(userinfo.ProfilePicture))
                {
                    notification.Icon = userinfo.ProfilePicture;
                }
                else
                {
                    notification.Icon = "/photodb/profile.jpg";
                }

                notification.DateTime = DateTime.UtcNow;
                await _context.WebNotificationsDb.AddAsync(notification);

                await _context.SaveChangesAsync();

                WebNotification webNotification = new WebNotification();
                webNotification.Title    = "Notification Sent to " + notification.To;
                webNotification.Message  = "";
                webNotification.From     = Constants.AppName;
                webNotification.Type     = "Notification";
                webNotification.DateTime = DateTime.UtcNow;
                webNotification.DateTime = TimeZoneInfo.ConvertTimeFromUtc(webNotification.DateTime,
                                                                           TimeZoneInfo.FindSystemTimeZoneById(userTimeZone));
                webNotification.DateTimeString = webNotification.DateTime.ToString("dd-MMM-yyyy HH:mm");
                if (String.IsNullOrEmpty(webNotification.Link))
                {
                    webNotification.Link = "/Notifications?Id=" + webNotification.Id;
                }
                await Clients.Caller.SendAsync("ReceiveMessage", JsonConvert.SerializeObject(webNotification));
            }
        }
        /// <summary>
        /// Adds the notification asynchronously.
        /// </summary>
        /// <param name="notification">The notification.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>The instance of <see cref="Task{Boolean}"/> representing an asynchronous operation.</returns>
        public async Task <bool> AddNotificationAsync(WebNotification notification, CancellationToken cancellationToken = default)
        {
            bool itemAdded = false;

            if (notification != null)
            {
                if (!cancellationToken.IsCancellationRequested && this.channel.Writer.TryWrite(notification))
                {
                    Log.ChannelMessageWritten(this.logger, notification.NotificationId);
                    itemAdded = true;
                }
            }

            return(itemAdded);
        }
Beispiel #20
0
        public static WebNotification FromDomainModel(this WebNotification obj, WebNotificationDomain domain)
        {
            if (obj == null)
            {
                obj = new WebNotification();
            }

            obj.WebNotificationId = domain.Id;
            obj.Seen           = domain.Seen;
            obj.DateSeen       = domain.DateSeen;
            obj.NotificationId = domain.NotificationId;
            obj.UserInfoId     = domain.UserInfoId;
            obj.UserTenantId   = domain.UserTenantId;

            return(obj);
        }
Beispiel #21
0
        public void ToWebNoticationValidEntity()
        {
            WebNotification webNotification = this.webNotificationItemEntity.ToWebNotification();

            Assert.IsTrue(webNotification.NotificationId.Equals(this.webNotificationItemEntity.NotificationId, StringComparison.Ordinal));
            Assert.IsTrue(webNotification.Title.Equals(this.webNotificationItemEntity.Title, StringComparison.Ordinal));
            Assert.IsTrue(webNotification.Body.Equals(this.webNotificationItemEntity.Body, StringComparison.Ordinal));
            Assert.AreEqual(webNotification.Properties.Count, this.webNotificationItemEntity.Properties.Count);
            Assert.IsTrue(webNotification.Sender.Name.Equals(this.webNotificationItemEntity.Sender.Name, StringComparison.Ordinal));
            Assert.IsTrue(webNotification.Sender.Email.Equals(this.webNotificationItemEntity.Sender.Email, StringComparison.Ordinal));
            Assert.IsTrue(webNotification.Sender.ObjectIdentifier.Equals(this.webNotificationItemEntity.Sender.ObjectIdentifier, StringComparison.Ordinal));
            Assert.IsTrue(webNotification.ExpiresOnUTCDate == this.webNotificationItemEntity.ExpiresOnUTCDate);
            Assert.IsTrue(webNotification.PublishOnUTCDate == this.webNotificationItemEntity.PublishOnUTCDate);
            Assert.IsTrue(webNotification.Priority == this.webNotificationItemEntity.Priority);
            Assert.IsTrue(webNotification.ReadStatus == this.webNotificationItemEntity.ReadStatus);
            Assert.IsTrue(webNotification.AppNotificationType.Equals(this.webNotificationItemEntity.AppNotificationType, StringComparison.OrdinalIgnoreCase));
        }
Beispiel #22
0
 public static WebNotificationDomain ToDomainModel(this WebNotification obj, NotificationDomain domain)
 {
     return(obj == null ? null : new WebNotificationDomain()
     {
         Id = obj.WebNotificationId,
         Seen = obj.Seen,
         DateSeen = obj.DateSeen,
         NotificationId = obj.NotificationId,
         UserInfoId = obj.UserInfoId,
         UserTenantId = obj.UserTenantId,
         Title = domain.Title,
         Content = domain.Content,
         ExternalId = domain.ExternalId,
         DateCreated = domain.DateCreated,
         DateModified = domain.DateModified,
         NotificationStatusId = domain.NotificationStatusId,
         NotificationTypeId = domain.NotificationTypeId
     });
 }
Beispiel #23
0
        public async Task <IActionResult> Remove(int Id)
        {
            string          userId             = User.FindFirst("sub")?.Value ?? "NoUser";
            WebNotification updateNotification =
                await _context.WebNotificationsDb.SingleOrDefaultAsync(n => n.Id == Id);

            if (updateNotification != null)
            {
                if (userId == updateNotification.To)
                {
                    _context.WebNotificationsDb.Remove(updateNotification);
                    await _context.SaveChangesAsync();

                    await _hubContext.Clients.User(userId).SendAsync("DeleteMessage", JsonConvert.SerializeObject(updateNotification));
                }
            }

            return(Ok());
        }
Beispiel #24
0
        public async Task <IActionResult> Index(int Id = 0)
        {
            string userId       = User.FindFirst("sub")?.Value ?? "NoUser";
            string userTimeZone = User.FindFirst("timezone")?.Value ?? "NoUser";
            List <WebNotification> notificationsList = await _context.WebNotificationsDb.Where(n => n.To == userId).ToListAsync();

            if (notificationsList.Any())
            {
                notificationsList = notificationsList.OrderBy(n => n.DateTime).ToList();
                notificationsList.Reverse();
                foreach (WebNotification notif in notificationsList)
                {
                    notif.DateTime = TimeZoneInfo.ConvertTimeFromUtc(notif.DateTime,
                                                                     TimeZoneInfo.FindSystemTimeZoneById(userTimeZone));
                    notif.DateTimeString = notif.DateTime.ToString("dd-MMM-yyyy HH:mm"); // Todo: Replace string format with global constant or user defined value
                    if (!notif.Icon.StartsWith("/") && !notif.Icon.StartsWith("http"))
                    {
                        notif.Icon = _imageStore.UriFor(notif.Icon, "profiles");
                    }
                }
            }
            if (Id != 0)
            {
                WebNotification notification = await _context.WebNotificationsDb.SingleOrDefaultAsync(n => n.Id == Id);

                if (notification.To == userId)
                {
                    notification.DateTime = TimeZoneInfo.ConvertTimeFromUtc(notification.DateTime,
                                                                            TimeZoneInfo.FindSystemTimeZoneById(userTimeZone));
                    notification.DateTimeString  = notification.DateTime.ToString("dd-MMM-yyyy HH:mm");
                    ViewBag.SelectedNotification = notification;
                    if (!notification.Icon.StartsWith("/") && !notification.Icon.StartsWith("http"))
                    {
                        notification.Icon = _imageStore.UriFor(notification.Icon, "profiles");
                    }
                }
            }

            return(View(notificationsList));
        }
        public async Task DeleteNotification(string notification)
        {
            string userId = Context.GetHttpContext().User.FindFirst("sub")?.Value ?? "NoUser";
            int    id;
            bool   idParsed = Int32.TryParse(notification, out id);

            if (idParsed)
            {
                WebNotification deleteNotification =
                    await _context.WebNotificationsDb.SingleOrDefaultAsync(n => n.Id == id);

                if (deleteNotification != null)
                {
                    if (userId == deleteNotification.To)
                    {
                        _context.WebNotificationsDb.Remove(deleteNotification);
                        await _context.SaveChangesAsync();

                        await Clients.User(userId).SendAsync("DeleteMessage", JsonConvert.SerializeObject(deleteNotification));
                    }
                }
            }
        }
        public async Task BroadcastNotificationAsync_WithValidNotification()
        {
            WebNotification webNotification = new WebNotification
            {
                NotificationId   = Guid.NewGuid().ToString(),
                Title            = "Test Title",
                Body             = "Test Body",
                PublishOnUTCDate = DateTime.UtcNow.AddDays(-1),
                ExpiresOnUTCDate = DateTime.UtcNow.AddDays(1),
                ReadStatus       = NotificationReadStatus.Read,
                Recipient        = new Person
                {
                    Name             = "Test Reciver",
                    Email            = "*****@*****.**",
                    ObjectIdentifier = Guid.NewGuid().ToString(),
                },
            };

            _ = this.clientMock.Setup(cli => cli.ReceiveNotificationsAsync(It.IsAny <IEnumerable <WebNotification> >())).Returns(Task.CompletedTask);
            await this.notificationsHub.BroadcastNotificationAsync(webNotification);

            Assert.IsTrue(this.loggerMock.Invocations.Count == 2);
        }
        private void Omnilink_OnZoneStatus(object sender, ZoneStatusEventArgs e)
        {
            if (e.Zone.IsTemperatureZone())
            {
                WebNotification.Send("temp", JsonConvert.SerializeObject(e.Zone.ToContract()));
                return;
            }

            switch (e.Zone.ZoneType)
            {
            case enuZoneType.EntryExit:
            case enuZoneType.X2EntryDelay:
            case enuZoneType.X4EntryDelay:
            case enuZoneType.Perimeter:
            case enuZoneType.Tamper:
            case enuZoneType.Auxiliary:
                WebNotification.Send("contact", JsonConvert.SerializeObject(e.Zone.ToContract()));
                break;

            case enuZoneType.AwayInt:
            case enuZoneType.NightInt:
                WebNotification.Send("motion", JsonConvert.SerializeObject(e.Zone.ToContract()));
                break;

            case enuZoneType.Water:
                WebNotification.Send("water", JsonConvert.SerializeObject(e.Zone.ToContract()));
                break;

            case enuZoneType.Fire:
                WebNotification.Send("smoke", JsonConvert.SerializeObject(e.Zone.ToContract()));
                break;

            case enuZoneType.Gas:
                WebNotification.Send("co", JsonConvert.SerializeObject(e.Zone.ToContract()));
                break;
            }
        }
 private void Omnilink_OnAreaStatus(object sender, AreaStatusEventArgs e)
 {
     WebNotification.Send("area", JsonConvert.SerializeObject(e.Area.ToContract()));
 }
 private void Omnilink_OnUnitStatus(object sender, UnitStatusEventArgs e)
 {
     WebNotification.Send("unit", JsonConvert.SerializeObject(e.Unit.ToContract()));
 }