/// <inheritdoc/>
        public Task SendNotificationsAsync(UserNotification[] userNotifications)
        {
            foreach (var userNotification in userNotifications)
            {
                try
                {
                    var onlineClients = _onlineClientManager.GetAllByUserId(userNotification);
                    foreach (var onlineClient in onlineClients)
                    {
                        var signalRClient = CommonHub.Clients.Client(onlineClient.ConnectionId);
                        if (signalRClient == null)
                        {
                            Logger.Debug("Can not get user " + userNotification.ToUserIdentifier() + " with connectionId " + onlineClient.ConnectionId + " from SignalR hub!");
                            continue;
                        }

                        //TODO: await call or not?
                        signalRClient.getNotification(userNotification);
                    }
                }
                catch (Exception ex)
                {
                    Logger.Warn("Could not send notification to user: " + userNotification.ToUserIdentifier());
                    Logger.Warn(ex.ToString(), ex);
                }
            }

            return Task.FromResult(0);
        }
        /// <inheritdoc/>
        public Task SendNotificationsAsync(UserNotification[] userNotifications)
        {
            foreach (var userNotification in userNotifications)
            {
                try
                {
                    var onlineClient = _onlineClientManager.GetByUserIdOrNull(userNotification.UserId);
                    if (onlineClient == null)
                    {
                        //User is not online. No problem, go to the next user.
                        continue;
                    }

                    var signalRClient = CommonHub.Clients.Client(onlineClient.ConnectionId);
                    if (signalRClient == null)
                    {
                        Logger.Debug("Can not get user " + userNotification.UserId + " from SignalR hub!");
                        continue;
                    }

                    //TODO: await call or not?
                    signalRClient.getNotification(userNotification);
                }
                catch (Exception ex)
                {
                    Logger.Warn("Could not send notification to userId: " + userNotification.UserId);
                    Logger.Warn(ex.ToString(), ex);
                }
            }

            return Task.FromResult(0);
        }
 protected void Page_Load(object sender, EventArgs e)
 {
     _NotifyId = m_EntityContextService.EntityID.ToString();
     using (new SessionScopeWrapper())
     {
         _CurrentEntity = EntityFactory.GetById<UserNotification>(_NotifyId);
     }
     SetTitleBar();
 }
Exemplo n.º 4
0
        public async Task<JsonResult> SignalRTest(string message)
        {
            var notification = new UserNotification
            {
                Id = Guid.NewGuid(),
                UserId = OwnerSession.UserId.GetValueOrDefault(),
                Notification = new Notification { Data = new NotificationData { Properties = { { "msg", message } } } }
            };

            await RealTimeNotifier.SendNotificationsAsync(new UserNotification[] { notification });

            return Json($"OK -- {OwnerSession.UserId}");
        }
        private void menuItem2_Click(object sender, EventArgs e)
        {
            OpenNETCF.WindowsCE.Notification.UserNotificationTrigger myTrig = new UserNotificationTrigger();

            if (!System.IO.File.Exists(txtApp.Text))
            {
                txtApp.BackColor = Color.Red;
                return;
            }
            myTrig.Application=txtApp.Text;
            
            myTrig.Arguments=txtArg.Text;

            try
            {
                myTrig.StartTime=DateTime.Parse(txtStart.Text);
            }
            catch (Exception)
            {
                txtStart.BackColor = Color.Red;                
                return;
            }
            try
            {
                myTrig.EndTime = DateTime.Parse(txtEnd.Text);
            }
            catch (Exception)
            {
                txtEnd.BackColor = Color.Red;
                return;
            }

            myTrig.Event= NotificationEvent.None;

            myTrig.Type=NotificationType.Time;

            UserNotification myUN = new UserNotification();
            

            int iRes = OpenNETCF.WindowsCE.Notification.Notify.SetUserNotification(myTrig, null);
            if (iRes != 0)
                MessageBox.Show("Added new UserNotification");
            else
                MessageBox.Show("Adding new UserNotification failed");

            this.DialogResult = DialogResult.OK;
            this.Close();
        }
Exemplo n.º 6
0
        public async Task <ICommandResult <Issue> > SendAsync(INotificationContext <Issue> context)
        {
            // Validate
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (context.Notification == null)
            {
                throw new ArgumentNullException(nameof(context.Notification));
            }

            if (context.Notification.Type == null)
            {
                throw new ArgumentNullException(nameof(context.Notification.Type));
            }

            if (context.Notification.To == null)
            {
                throw new ArgumentNullException(nameof(context.Notification.To));
            }

            // Ensure correct notification provider
            if (!context.Notification.Type.Name.Equals(WebNotifications.IssueSpam.Name, StringComparison.Ordinal))
            {
                return(null);
            }

            // Create result
            var result = new CommandResult <Issue>();

            var baseUri = await _urlHelper.GetBaseUrlAsync();

            var url = _urlHelper.GetRouteUrl(baseUri, new RouteValueDictionary()
            {
                ["area"]       = "Plato.Issues",
                ["controller"] = "Home",
                ["action"]     = "Display",
                ["opts.id"]    = context.Model.Id,
                ["opts.alias"] = context.Model.Alias
            });

            //// Build notification
            var userNotification = new UserNotification()
            {
                NotificationName = context.Notification.Type.Name,
                UserId           = context.Notification.To.Id,
                Title            = S["Possible SPAM"].Value,
                Message          = S["An issue has been detected as SPAM!"],
                Url           = url,
                CreatedUserId = context.Notification.From?.Id ?? 0,
                CreatedDate   = DateTimeOffset.UtcNow
            };

            // Create notification
            var userNotificationResult = await _userNotificationManager.CreateAsync(userNotification);

            if (userNotificationResult.Succeeded)
            {
                return(result.Success(context.Model));
            }

            return(result.Failed(userNotificationResult.Errors?.ToArray()));
        }
Exemplo n.º 7
0
        public async Task <ICommandResult <Badge> > SendAsync(INotificationContext <Badge> context)
        {
            // Validate
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (context.Notification == null)
            {
                throw new ArgumentNullException(nameof(context.Notification));
            }

            if (context.Notification.Type == null)
            {
                throw new ArgumentNullException(nameof(context.Notification.Type));
            }

            if (context.Notification.To == null)
            {
                throw new ArgumentNullException(nameof(context.Notification.To));
            }

            // Ensure correct notification provider
            if (!context.Notification.Type.Name.Equals(WebNotifications.NewBadge.Name, StringComparison.Ordinal))
            {
                return(null);
            }

            // Create result
            var result = new CommandResult <Badge>();

            var baseUri = await _urlHelper.GetBaseUrlAsync();

            var url = _urlHelper.GetRouteUrl(baseUri, new RouteValueDictionary()
            {
                ["area"]       = "Plato.Users.Badges",
                ["controller"] = "Profile",
                ["action"]     = "Index",
                ["opts.id"]    = context.Notification.To.Id,
                ["opts.alias"] = context.Notification.To.Alias
            });

            //// Build notification
            var userNotification = new UserNotification()
            {
                NotificationName = context.Notification.Type.Name,
                UserId           = context.Notification.To.Id,
                Title            = context.Model.Title,
                Message          = $"{S["You've earned the"].Value} '{context.Model.Title}' {S["badge"].Value}",
                Url           = url,
                CreatedUserId = context.Notification.From?.Id ?? 0,
                CreatedDate   = DateTimeOffset.UtcNow
            };

            // Create notification
            var userNotificationResult = await _userNotificationManager.CreateAsync(userNotification);

            if (userNotificationResult.Succeeded)
            {
                return(result.Success(context.Model));
            }

            return(result.Failed(userNotificationResult.Errors?.ToArray()));
        }
 public void Add(UserNotification n) {
     _notifications.Add(n);
 }
Exemplo n.º 9
0
 public Task SendAsync(UserNotification userNotification)
 {
     return(Task.CompletedTask);
 }
Exemplo n.º 10
0
        public async Task <Ticket> Update(Ticket Ticket)
        {
            if (!await TicketValidator.Update(Ticket))
            {
                return(Ticket);
            }
            try
            {
                var oldData = await UOW.TicketRepository.Get(Ticket.Id);

                await UOW.Begin();

                DateTime Now = StaticParams.DateTimeNow;
                // Gán thời gian xử lý và thời gian phản hồi cho ticket từ SLAPolicy
                SLAPolicy SLAPolicy = await UOW.SLAPolicyRepository.GetByTicket(Ticket);

                if (SLAPolicy != null)
                {
                    //Ticket.SLAPolicyId = SLAPolicy.Id;
                    Ticket.FirstResponeTime = oldData.CreatedAt.AddMinutes(Utils.ConvertSLATimeToMenute(SLAPolicy.FirstResponseTime.Value, SLAPolicy.FirstResponseUnitId.Value));
                    Ticket.ResolveTime      = oldData.CreatedAt.AddMinutes(Utils.ConvertSLATimeToMenute(SLAPolicy.ResolveTime.Value, SLAPolicy.ResolveUnitId.Value));
                }
                // Ticket chuyển từ trạng thái hoạt động sang dừng
                if (!Ticket.IsWork.Value && oldData.IsWork.Value)
                {
                    Ticket.LastHoldingAt = Now;
                }
                // Ticket chuyển từ trạng thái dừng sang hoạt động
                else if (Ticket.IsWork.Value && !oldData.IsWork.Value)
                {
                    Ticket.FirstResponeTime = Now.AddMinutes(oldData.FirstRespTimeRemaining.Value);
                    Ticket.ResolveTime      = Now.AddMinutes(oldData.ResolveTimeRemaining.Value);
                    Ticket.HoldingTime      = oldData.HoldingTime + (long)(Now.Subtract(oldData.LastHoldingAt.Value).TotalMinutes);
                }
                // Lưu lại lịch sử ticket
                Ticket.TicketOfUsers = new List <TicketOfUser>();
                Ticket.TicketOfUsers.Add(
                    new TicketOfUser()
                {
                    TicketStatusId = Ticket.TicketStatusId,
                    UserId         = Ticket.UserId,
                    Notes          = Ticket.Notes,
                    TicketId       = Ticket.Id
                }
                    );
                // Đóng ticket
                if (Ticket.TicketStatusId == TicketStatusEnum.RESOLVED.Id || Ticket.TicketStatusId == TicketStatusEnum.CLOSED.Id)
                {
                    Ticket.ResolvedAt    = Now;
                    Ticket.ResolveMinute = (long)(Now.Subtract(oldData.CreatedAt).TotalMinutes);
                    Ticket.IsClose       = true;

                    var ot = (long)(Now.Subtract(Ticket.ResolveTime.Value).TotalMinutes);
                    if (ot > 0)
                    {
                        Ticket.SLAOverTime = ot;
                    }

                    if (Ticket.TicketStatusId == TicketStatusEnum.CLOSED.Id)
                    {
                        Ticket.closedAt = Now;
                    }

                    // Update trạng thái SLA
                    if (oldData.ResolveTime < Now)
                    {
                        Ticket.SLAStatusId = SLAStatusEnum.Fail.Id;
                    }
                    else
                    {
                        Ticket.SLAStatusId = SLAStatusEnum.Success.Id;
                    }
                }
                // Mở lại ticket
                if (Ticket.TicketStatusId != TicketStatusEnum.RESOLVED.Id && Ticket.TicketStatusId != TicketStatusEnum.CLOSED.Id && oldData.IsClose.Value)
                {
                    Ticket.ReraisedTimes = oldData.ReraisedTimes.Value + 1;
                    Ticket.IsClose       = false;
                }

                // Update thời gian phản hồi còn lại và thời gian xử lý còn lại
                var frtr = (long)(oldData.FirstResponeTime.Value.Subtract(Now).TotalMinutes);
                Ticket.FirstRespTimeRemaining = frtr < 0 ? 0 : frtr;
                var rtr = (long)(oldData.ResolveTime.Value.Subtract(Now).TotalMinutes);
                Ticket.ResolveTimeRemaining = rtr < 0 ? 0 : rtr;

                await UOW.TicketRepository.Update(Ticket);

                await UOW.Commit();

                Ticket = await UOW.TicketRepository.Get(Ticket.Id);

                // Push noti ticket đã sử dụng
                NotifyUsed(Ticket);

                // Thông báo cho người phụ trách ticket
                List <UserNotification> UserNotifications = new List <UserNotification>();
                var AssignUser = await UOW.AppUserRepository.Get(Ticket.UserId);

                var CurrentUser = await UOW.AppUserRepository.Get(CurrentContext.UserId);

                List <long> RecipientIds = new List <long>();
                RecipientIds.Add(Ticket.UserId);
                RecipientIds.Add(Ticket.CreatorId);
                foreach (var id in RecipientIds)
                {
                    UserNotification NotificationUtils = new UserNotification
                    {
                        TitleWeb    = $"Thông báo từ CRM",
                        ContentWeb  = $"Ticket [{Ticket.TicketNumber} - {Ticket.Name} - {Ticket.TicketIssueLevel.Name}] đã được gán cho {AssignUser.DisplayName} bởi {CurrentUser.DisplayName}",
                        LinkWebsite = $"{TicketRoute.Detail}/*".Replace("*", Ticket.Id.ToString()),
                        Time        = Now,
                        Unread      = true,
                        SenderId    = CurrentContext.UserId,
                        RecipientId = id
                    };
                    UserNotifications.Add(NotificationUtils);
                }

                await NotificationService.BulkSend(UserNotifications);

                await Logging.CreateAuditLog(Ticket, oldData, nameof(TicketService));

                return(Ticket);
            }
            catch (Exception ex)
            {
                await UOW.Rollback();

                if (ex.InnerException == null)
                {
                    await Logging.CreateSystemLog(ex, nameof(TicketService));

                    throw new MessageException(ex);
                }
                else
                {
                    await Logging.CreateSystemLog(ex.InnerException, nameof(TicketService));

                    throw new MessageException(ex.InnerException);
                }
            }
        }
Exemplo n.º 11
0
        public async Task <ICommandResult <Comment> > SendAsync(INotificationContext <Comment> context)
        {
            // Validate
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (context.Notification == null)
            {
                throw new ArgumentNullException(nameof(context.Notification));
            }

            if (context.Notification.Type == null)
            {
                throw new ArgumentNullException(nameof(context.Notification.Type));
            }

            if (context.Notification.To == null)
            {
                throw new ArgumentNullException(nameof(context.Notification.To));
            }

            // Ensure correct notification provider
            if (!context.Notification.Type.Name.Equals(WebNotifications.CommentSpam.Name, StringComparison.Ordinal))
            {
                return(null);
            }

            // Create result
            var result = new CommandResult <Comment>();

            // Get entity for reply
            var entity = await _entityStore.GetByIdAsync(context.Model.EntityId);

            // Ensure we found the entity
            if (entity == null)
            {
                return(result.Failed(
                           $"No entity with id '{context.Model.EntityId}' exists. Failed to send reply spam web notification."));
            }

            var baseUri = await _urlHelper.GetBaseUrlAsync();

            var url = _urlHelper.GetRouteUrl(baseUri, new RouteValueDictionary()
            {
                ["area"]         = "Plato.Articles",
                ["controller"]   = "Home",
                ["action"]       = "Reply",
                ["opts.id"]      = entity.Id,
                ["opts.alias"]   = entity.Alias,
                ["opts.replyId"] = context.Model.Id
            });

            //// Build notification
            var userNotification = new UserNotification()
            {
                NotificationName = context.Notification.Type.Name,
                UserId           = context.Notification.To.Id,
                Title            = S["Possible SPAM"].Value,
                Message          = S["Am article comment has been detected as SPAM!"],
                Url           = url,
                CreatedUserId = context.Notification.From?.Id ?? 0,
                CreatedDate   = DateTimeOffset.UtcNow
            };

            // Create notification
            var userNotificationResult = await _userNotificationManager.CreateAsync(userNotification);

            if (userNotificationResult.Succeeded)
            {
                return(result.Success(context.Model));
            }

            return(result.Failed(userNotificationResult.Errors?.ToArray()));
        }
Exemplo n.º 12
0
 public void AddAlert(UserNotification notification)
 {
     notification.alertid    = Guid.NewGuid().ToString();
     notification.createtime = DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture);
     _getNotificationDetails.InsertOne(notification, _notificationCollection);
 }
Exemplo n.º 13
0
    /**
     * Called when Pushe is registered.
     */
    private void OnPusheRegisteredSuccessfully()
    {
        PusheUnity.Log(" --- Pushe has been REGISTERED to server successfully --- ");
        var adId = PusheUnity.GetAdvertisingId();

        PusheUnity.Log("Ad id: " + adId);
        var deviceId = PusheUnity.GetDeviceId();

        PusheUnity.Log("Device id : " + deviceId);

        // Pushe Notification

        PusheUnity.Log("Notification enabled? " + PusheNotification.IsNotificationEnabled());
        PusheUnity.Log("Custom sound enabled? " + PusheNotification.IsCustomSoundEnabled());
        // PusheNotification.CreateNotificationChannel("CustomChannel", "CustomChannel");
        PusheUnity.Log("Sending d2d");
        PusheNotification.SendNotificationToUser(UserNotification.WithDeviceId(PusheUnity.GetDeviceId()).SetTitle("Title").SetContent("Content"));
        // Analytics
        PusheAnalytics.SendEvent("Some_Event");
        PusheAnalytics.SendEcommerceData("EcommerceData", 12.0);

        PusheUnity.Log("Subscribing to test1");
        PusheUnity.Subscribe("test1");

        PusheUnity.Log("Set 123123 as custom id");
        PusheUnity.SetCustomId("123123");
        PusheUnity.Log("CustomId is: " + PusheUnity.GetCustomId());

        var tags = new Dictionary <string, string> {
            { "name", "Mohammad" }, { "age", "25" }, { "birthday", "1435187386" }
        };

        PusheUnity.AddTags(tags);

        PusheUnity.RemoveTags("name", "age");

        PusheUnity.Log("Tags: " + PusheUnity.GetSubscribedTags());
        PusheUnity.Log("Topics: " + string.Join(",", PusheUnity.GetSubscribedTopics()));

        // InAppMessaging
        PusheInAppMessaging.DisableInAppMessaging();
        PusheUnity.Log("Is in app messaging enabled?" + PusheInAppMessaging.IsInAppMessagingEnabled());
        PusheInAppMessaging.EnableInAppMessaging();
        PusheUnity.Log("Is in app messaging enabled? " + PusheInAppMessaging.IsInAppMessagingEnabled());
        PusheInAppMessaging.TriggerEvent("qqq");
        PusheInAppMessaging.SetInAppMessagingListener(new InAppMessagingListener());

        // FCM token and ...
        var fcmToken      = PusheUnity.GetFcmToken();
        var hmsToken      = PusheUnity.GetHmsToken();
        var activeService = PusheUnity.GetActiveService();

        PusheUnity.Log("Fcm token: " + fcmToken + "\nHms token: " + hmsToken + "\nActive service: " + activeService);

        // Foreground awareness feature of notification
        PusheUnity.Log("Are all notifications aware of foreground state? " + PusheUnity.IsForceForegroundAware());
        PusheUnity.Log("Toggle to true");
        PusheUnity.EnableNotificationForceForegroundAware();
        PusheUnity.Log("Are all notifications aware of foreground state? " + PusheUnity.IsForceForegroundAware());
        PusheUnity.Log("Toggle back to false");
        PusheUnity.DisableNotificationForceForegroundAware();
        PusheUnity.Log("Are all notifications aware of foreground state? " + PusheUnity.IsForceForegroundAware());
    }
Exemplo n.º 14
0
 public Task SendNotification(UserNotification request, CancellationToken cancellationToken)
 {
     return(Task.Run(() => TrySendNotification(request, cancellationToken)));
 }
Exemplo n.º 15
0
 public JsonResult _UpdateUserNotification(UserNotification ins)
 {
     ins = notifyRep.UpdateUserNotification(ins);
     return(Json(new GridModel(commonRep.GetUserNotifications())));
 }
Exemplo n.º 16
0
 public static UserNotification[] Get(
     Model.User.User user, bool seen = false, int limit = 10
     )
 {
     return(UserNotification.Get(user, seen, limit));
 }
Exemplo n.º 17
0
 public static UserNotification FindByGuid(string guid) => UserNotification.FindByGuid(guid);
Exemplo n.º 18
0
 public static UserNotification Find(int id) => UserNotification.Find(id);
Exemplo n.º 19
0
 public static UserNotification Create(
     Model.User.User user, string title, string content, UserNotificationType type = UserNotificationType.Info
     )
 {
     return(Find(UserNotification.Create(user, title, content, type)));
 }
Exemplo n.º 20
0
 public bool CanSend(UserNotification notification, NotificationSetting setting, User user, App app)
 {
     return(!string.IsNullOrWhiteSpace(app.WebhookUrl));
 }
Exemplo n.º 21
0
 public virtual Task InsertUserNotificationAsync(UserNotification userNotification)
 {
     _userNotificationRepository.Add(userNotification);
     return(Task.CompletedTask);
 }
Exemplo n.º 22
0
        public void Notify(Notification notification)
        {
            var userNotification = new UserNotification(notification, this);

            UserNotifications.Add(userNotification);
        }
Exemplo n.º 23
0
        public async Task <Ticket> Create(Ticket Ticket)
        {
            if (!await TicketValidator.Create(Ticket))
            {
                return(Ticket);
            }

            try
            {
                await UOW.Begin();

                var newId = await TicketGeneratedIdService.GetNewTicketId();

                Ticket.TicketNumber   = newId.Id.ToString().PadLeft(6, '0');
                Ticket.UserId         = CurrentContext.UserId;
                Ticket.CreatorId      = CurrentContext.UserId;
                Ticket.Subject        = "";
                Ticket.SLA            = Ticket.TicketIssueLevel.SLA;
                Ticket.IsAlerted      = false;
                Ticket.IsAlertedFRT   = false;
                Ticket.IsEscalated    = false;
                Ticket.IsEscalatedFRT = false;
                Ticket.IsClose        = false;
                Ticket.IsOpen         = true;
                Ticket.IsWait         = false;
                Ticket.IsWork         = true;
                Ticket.ReraisedTimes  = 0;
                Ticket.HoldingTime    = 0;
                Ticket.TicketStatusId = TicketStatusEnum.NEW.Id;
                Ticket.TicketOfUsers  = new List <TicketOfUser>();
                Ticket.TicketOfUsers.Add(
                    new TicketOfUser()
                {
                    TicketStatusId = TicketStatusEnum.NEW.Id,
                    UserId         = Ticket.UserId
                }
                    );
                SLAPolicy SLAPolicy = await UOW.SLAPolicyRepository.GetByTicket(Ticket);

                DateTime Now = StaticParams.DateTimeNow;
                if (SLAPolicy != null)
                {
                    // Ticket.SLAPolicyId = SLAPolicy.Id;
                    Ticket.FirstResponeTime = Now.AddMinutes(Utils.ConvertSLATimeToMenute(SLAPolicy.FirstResponseTime.Value, SLAPolicy.FirstResponseUnitId.Value));
                    Ticket.ResolveTime      = Now.AddMinutes(Utils.ConvertSLATimeToMenute(SLAPolicy.ResolveTime.Value, SLAPolicy.ResolveUnitId.Value));
                }
                await UOW.TicketRepository.Create(Ticket);

                await TicketGeneratedIdService.UpdateUsed(int.Parse(Ticket.TicketNumber));

                await UOW.Commit();

                Ticket = await UOW.TicketRepository.Get(Ticket.Id);

                NotifyUsed(Ticket);
                var CurrentUser = await UOW.AppUserRepository.Get(CurrentContext.UserId);

                var RecipientIds = await UOW.PermissionRepository.ListAppUser(TicketRoute.Update);

                List <UserNotification> UserNotifications = new List <UserNotification>();
                //foreach (var id in RecipientIds)
                //{
                UserNotification NotificationUtils = new UserNotification
                {
                    TitleWeb    = $"Thông báo từ CRM",
                    ContentWeb  = $"Ticket [{Ticket.TicketNumber} - {Ticket.Name} - {Ticket.TicketIssueLevel.Name}] đã được thêm mới lên hệ thống bởi {CurrentUser.DisplayName}",
                    LinkWebsite = $"{TicketRoute.Detail}/*".Replace("*", Ticket.Id.ToString()),
                    Time        = Now,
                    Unread      = true,
                    SenderId    = CurrentContext.UserId,
                    RecipientId = CurrentContext.UserId,
                    RowId       = Guid.NewGuid(),
                };
                UserNotifications.Add(NotificationUtils);
                //}

                List <EventMessage <UserNotification> > EventUserNotifications = UserNotifications.Select(x => new EventMessage <UserNotification>(x, x.RowId)).ToList();
                RabbitManager.PublishList(EventUserNotifications, RoutingKeyEnum.UserNotificationSend);


                await Logging.CreateAuditLog(Ticket, new { }, nameof(TicketService));

                return(Ticket);
            }
            catch (Exception ex)
            {
                if (ex.InnerException == null)
                {
                    await Logging.CreateSystemLog(ex, nameof(TicketService));

                    throw new MessageException(ex);
                }
                else
                {
                    await Logging.CreateSystemLog(ex.InnerException, nameof(TicketService));

                    throw new MessageException(ex.InnerException);
                }
            }
        }
Exemplo n.º 24
0
 private Task UpdateAsync(UserNotification notification, ProcessStatus status, string?reason = null)
 {
     return(userNotificationStore.CollectAndUpdateAsync(notification, Name, status, reason));
 }
Exemplo n.º 25
0
        public async Task <ICommandResult <ReportSubmission <Comment> > > SendAsync(INotificationContext <ReportSubmission <Comment> > context)
        {
            // Validate
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (context.Notification == null)
            {
                throw new ArgumentNullException(nameof(context.Notification));
            }

            if (context.Notification.Type == null)
            {
                throw new ArgumentNullException(nameof(context.Notification.Type));
            }

            if (context.Notification.To == null)
            {
                throw new ArgumentNullException(nameof(context.Notification.To));
            }

            // Ensure correct notification provider
            if (!context.Notification.Type.Name.Equals(WebNotifications.IssueCommentReport.Name, StringComparison.Ordinal))
            {
                return(null);
            }

            // Get entity for reply
            var entity = await _entityStore.GetByIdAsync(context.Model.What.EntityId);

            // Ensure entity exists
            if (entity == null)
            {
                return(null);
            }

            // Create result
            var result = new CommandResult <ReportSubmission <Comment> >();

            var baseUri = await _urlHelper.GetBaseUrlAsync();

            var url = _urlHelper.GetRouteUrl(baseUri, new RouteValueDictionary()
            {
                ["area"]         = "Plato.Issues",
                ["controller"]   = "Home",
                ["action"]       = "Reply",
                ["opts.id"]      = entity.Id,
                ["opts.alias"]   = entity.Alias,
                ["opts.replyId"] = context.Model.What.Id
            });

            // Get reason given text
            var reasonText = S["Reply Reported"];

            if (ReportReasons.Reasons.ContainsKey(context.Model.Why))
            {
                reasonText = S[ReportReasons.Reasons[context.Model.Why]];
            }

            // Build notification
            var userNotification = new UserNotification()
            {
                NotificationName = context.Notification.Type.Name,
                UserId           = context.Notification.To.Id,
                Title            = reasonText.Value,
                Message          = S["A comment has been reported!"],
                Url           = url,
                CreatedUserId = context.Notification.From?.Id ?? 0,
                CreatedDate   = DateTimeOffset.UtcNow
            };

            // Create notification
            var userNotificationResult = await _userNotificationManager.CreateAsync(userNotification);

            if (userNotificationResult.Succeeded)
            {
                return(result.Success(context.Model));
            }

            return(result.Failed(userNotificationResult.Errors?.ToArray()));
        }
Exemplo n.º 26
0
        private void changeReqGrid_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            DataGridView dgv = sender as DataGridView;

            if (dgv.CurrentRow.Selected)
            {
                if (Userglobals.uname.Equals(""))
                {
                    MessageBox.Show("You must Login first!", "Develop change requests", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                }
                else
                {
                    if (Userglobals.uid > 0 && (Userglobals.priv.Equals("TCH") || Userglobals.priv.Equals("ADM")))
                    {
                        int      uid       = Userglobals.uid;
                        Object   startedDT = changeReqGrid.Rows[e.RowIndex].Cells[7].Value;
                        Object   endedDT   = changeReqGrid.Rows[e.RowIndex].Cells[8].Value;
                        DateTime dt;
                        int      projId = Int32.Parse(changeReqGrid.Rows[e.RowIndex].Cells[0].Value.ToString());
                        int      reqId  = Int32.Parse(changeReqGrid.Rows[e.RowIndex].Cells[1].Value.ToString());

                        if (!DateTime.TryParse(startedDT.ToString(), out dt))
                        {
                            bool requested, adminView, status;

                            status = getReqStatus(projId, reqId, out adminView, out requested);

                            if (!requested)
                            {
                                DialogResult r = MessageBox.Show("You need permission to start this change request development!\nRequest Permission?", "Request Permission", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                                switch (r)
                                {
                                case DialogResult.Yes:

                                    UserNotification notification = new UserNotification(uid, 1, false, projId, reqId);

                                    Database.addNotification(notification);

                                    addReqNotify.Icon           = SystemIcons.Application;
                                    addReqNotify.BalloonTipText = "Your request successfully sent!";
                                    addReqNotify.ShowBalloonTip(500);

                                    break;

                                case DialogResult.No:
                                    break;

                                default:
                                    break;
                                }
                            }
                            else if (!adminView)
                            {
                                MessageBox.Show("Your request is still pending!", "Request Permission", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                            else if (!status)
                            {
                                MessageBox.Show("Your request has been declined!", "Request Permission", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                            else
                            {
                                DialogResult result = MessageBox.Show("Start coding this change request NOW?", "Start Developing Change Requests", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                                switch (result)
                                {
                                case DialogResult.Yes:

                                    ProjectRequest startReq = new ProjectRequest(new Project(projId), reqId, new Staff(uid));

                                    Database.startCodingChangeRequest(startReq);

                                    changeReqGrid.DataSource = getChangeRequests();

                                    changeReqGrid.Columns[0].Visible = false;
                                    changeReqGrid.Columns[1].Visible = false;
                                    markSeen();

                                    addReqNotify.Icon           = SystemIcons.Application;
                                    addReqNotify.BalloonTipText = "Change Request Development Started!";
                                    addReqNotify.ShowBalloonTip(1000);

                                    break;

                                case DialogResult.No:
                                    break;

                                default:
                                    break;
                                }
                            }
                        }
                        else if (!DateTime.TryParse(endedDT.ToString(), out dt))
                        {
                            DialogResult result = MessageBox.Show("End coding this change request NOW?\n" + uid, "End Developing Change Requests", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                            switch (result)
                            {
                            case DialogResult.Yes:

                                ProjectRequest endReq = new ProjectRequest(new Project(projId), reqId, new Staff(uid));

                                if (Database.endCodingChangeRequest(endReq))
                                {
                                    changeReqGrid.DataSource = getChangeRequests();

                                    changeReqGrid.Columns[0].Visible = false;
                                    changeReqGrid.Columns[1].Visible = false;
                                    changeGridRowColors("Change");
                                    markSeen();

                                    addReqNotify.Icon           = SystemIcons.Application;
                                    addReqNotify.BalloonTipText = "Change Request Development Ended!";
                                    addReqNotify.ShowBalloonTip(1000);
                                }
                                else
                                {
                                    changeReqGrid.DataSource = getChangeRequests();

                                    changeReqGrid.Columns[0].Visible = false;
                                    changeReqGrid.Columns[1].Visible = false;
                                    changeGridRowColors("Change");
                                    markSeen();
                                }

                                break;

                            case DialogResult.No:
                                break;

                            default:
                                break;
                            }
                        }
                        else
                        {
                            MessageBox.Show("This Change Request is already Developed!", "Developing Change Requests", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                        }
                    }
                }
            }
        }
 public NotificationCollection(UserNotification notification) { _notifications.Add(notification); }
Exemplo n.º 28
0
 public async Task Add(UserNotification notification)
 {
     await _repository.Add(notification);
 }
Exemplo n.º 29
0
        public async Task <ICommandResult <Comment> > SendAsync(INotificationContext <Comment> context)
        {
            // Ensure correct notification provider
            if (!context.Notification.Type.Name.Equals(WebNotifications.NewMention.Name, StringComparison.Ordinal))
            {
                return(null);
            }

            // We always need a model
            if (context.Model == null)
            {
                return(null);
            }

            // The reply should be visible
            if (context.Model.IsHidden())
            {
                return(null);
            }

            // Get entity for reply
            var entity = await _entityStore.GetByIdAsync(context.Model.EntityId);

            // We need an entity
            if (entity == null)
            {
                return(null);
            }

            // The entity should be visible
            if (entity.IsHidden())
            {
                return(null);
            }

            // Create result
            var result = new CommandResult <Comment>();

            // Build user notification
            var userNotification = new UserNotification()
            {
                NotificationName = context.Notification.Type.Name,
                UserId           = context.Notification.To.Id,
                Title            = S["New Mention"].Value,
                Message          = S["You've been mentioned by "].Value + context.Model.CreatedBy.DisplayName,
                CreatedUserId    = context.Model.CreatedUserId,
                Url = _contextFacade.GetRouteUrl(new RouteValueDictionary()
                {
                    ["area"]         = "Plato.Articles",
                    ["controller"]   = "Home",
                    ["action"]       = "Reply",
                    ["opts.id"]      = entity.Id,
                    ["opts.alias"]   = entity.Alias,
                    ["opts.replyId"] = context.Model.Id
                })
            };

            var userNotificationResult = await _userNotificationManager.CreateAsync(userNotification);

            if (userNotificationResult.Succeeded)
            {
                return(result.Success(context.Model));
            }

            return(result.Failed(userNotificationResult.Errors?.ToArray()));
        }
 public Task SendNotificationsAsync(UserNotification[] userNotifications)
 {
     return Task.FromResult(0);
 }
Exemplo n.º 31
0
 private void SendEmailNotification(UserNotification userNotification)
 {
 }
Exemplo n.º 32
0
 public BaseResponse <UserNotification> Add(UserNotification model)
 {
     return(shareService.AddUserNotification(model));
 }
Exemplo n.º 33
0
 public async Task Set(UserNotification item)
 {
     Logger.Info("updating grain state - {item}", item);
     State.UserNotification = item;
     await WriteStateAsync();
 }
Exemplo n.º 34
0
        public IActionResult Create(CommentsViewModel model)
        {
            var userId = GetLoggedInUser().Id;

            var post = GetPost();

            var comment = new Comment
            {
                UserId      = userId,
                PostId      = post.ID,
                CommentDate = DateTime.Now,
                CommentText = model.CommentText
            };

            post.Comments.Add(comment);
            post.CommentsCount++;
            _context.Update(post);


            var notification = new Notification
            {
                Type     = NotificationType.PostCommented,
                DateTime = DateTime.Now,
                Post     = post,
                ActorId  = userId
            };

            _context.Notifications.Add(notification);


            var postCreator = _context.Posts
                              .Where(p => p.ID == post.ID)
                              .Select(p => p.Artist)
                              .SingleOrDefault();

            var userNotification = new UserNotification
            {
                NotificationId = notification.Id,
                UserId         = postCreator.Id
            };

            postCreator.UserNotifications.Add(userNotification);
            _context.Update(postCreator);



            _context.SaveChanges();

            var comments = _context.Comments
                           .Where(c => c.PostId == post.ID)
                           .Include(c => c.User)
                           .ToList();

            var viewModel = new CommentsViewModel
            {
                Comments    = comments.OrderByDescending(c => c.CommentDate),
                CommentText = null,
                Post        = post,
                PostId      = post.ID
            };

            return(View(viewModel));
        }
Exemplo n.º 35
0
 public bool CanSend(UserNotification notification, NotificationSetting setting, User user, App app)
 {
     return(!notification.Silent && user.WebPushSubscriptions.Count > 0);
 }
Exemplo n.º 36
0
        public IHttpActionResult PostNotification(string message, DateTime notificationdt, string rawId)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            // Insert new notification to db
            var newNotification = new Notification {
                Message = message, NotificationTime = notificationdt, UserID = rawId
            };

            db.Notifications.Add(newNotification);
            db.SaveChanges();


            int notificationid = newNotification.NotificationID; // new notification ID



            string[]    userids = rawId.Split(','); // Get a list of userids from userid<string>
            List <User> users   = new List <User>();

            // update UserNotification entries for each userid
            foreach (string s in userids)
            {
                int  userid   = int.Parse(s);
                var  username = db.Users.Find(userid).Username;
                User user     = new Models.User {
                    UserID = int.Parse(s), Username = username
                };
                users.Add(user);

                UserNotification un = new UserNotification {
                    UserID = int.Parse(s), NotificationID = notificationid, IsRead = false
                };
                db.UserNotifications.Add(un);
            }
            db.SaveChanges();

            //Send Http Post to Notification Hub
            string URI = "http://localhost:62433/api/Notifications/" + notificationid;


            var httpWebRequest = (HttpWebRequest)WebRequest.Create(URI);

            httpWebRequest.ContentType = "text/json";
            httpWebRequest.Method      = "POST";

            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                string json = new JavaScriptSerializer().Serialize(new
                {
                    NotificationID   = notificationid,
                    Message          = message,
                    NotificationTime = notificationdt,
                    Users            = users
                });


                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();
            }

            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            var streamReader = new StreamReader(httpResponse.GetResponseStream());

            {
                var result = streamReader.ReadToEnd();
            }

            return(CreatedAtRoute("DefaultApi", new { id = notificationid }, newNotification));
        }
Exemplo n.º 37
0
 public virtual void onMessage( UserNotification message, QuickFix.SessionID session ) 
   { throw new QuickFix.UnsupportedMessageType(); }
Exemplo n.º 38
0
 public EmailJob(UserNotification notification)
 {
     Notification = notification;
 }
Exemplo n.º 39
0
 protected void Page_Load(object sender, EventArgs e)
 {
     m_SLXUserService = ApplicationContext.Current.Services.Get<IUserService>() as SLXUserService;
     _UserId = m_SLXUserService.GetUser().Id.ToString();
     _ActivityId = m_EntityContextService.EntityID.ToString();
     _CurrentActivity = Activity.GetActivityFromID(_ActivityId);
     _NotifyId = (Page.Request.QueryString.Get("notifyid"));
     _UserNotify = (UserNotification)EntityFactory.GetById(typeof(UserNotification), _NotifyId);
 }
Exemplo n.º 40
0
        public void Initialize(UserNotification userNotification, List <User> users, List <Group> groups, double width, Action hideCallback)
        {
            this._userNotification  = userNotification;
            this._users             = users;
            this._groups            = groups;
            this._width             = width;
            this._hideCallback      = hideCallback;
            this._newsfeed          = this._userNotification.newsfeed;
            this._images            = this._newsfeed.images;
            this._title             = this._newsfeed.title;
            this._message           = this._newsfeed.message;
            this._button            = this._newsfeed.button;
            this._usersDescription  = this._newsfeed.users_description;
            this._groupsDescription = this._newsfeed.groups_description;
            this._hasTitle          = !string.IsNullOrWhiteSpace(this._title);
            this._hasMessage        = !string.IsNullOrWhiteSpace(this._message);
            List <UserNotificationImage> images = this._images;

            // ISSUE: explicit non-virtual call
            this._hasImages = images != null && images.Count > 0;
            UserNotificationButton button1 = this._button;

            this._hasButton = !string.IsNullOrWhiteSpace(button1 != null ? button1.title :  null) && this._button.action != null;
            List <User> users1 = this._users;

            // ISSUE: explicit non-virtual call
            this._hasUsers = users1 != null && users1.Count > 0;
            List <Group> groups1 = this._groups;

            // ISSUE: explicit non-virtual call
            this._hasGroups            = groups1 != null && groups1.Count > 0;
            this._hasUsersDescription  = !string.IsNullOrWhiteSpace(this._usersDescription);
            this._hasGroupsDescription = !string.IsNullOrWhiteSpace(this._groupsDescription);
            UserNotificationButton button2 = this._button;
            int num1;

            if (button2 == null)
            {
                num1 = 0;
            }
            else
            {
                UserNotificationButtonAction     action           = button2.action;
                UserNotificationButtonActionType?nullable         = action != null ? new UserNotificationButtonActionType?(action.type) : new UserNotificationButtonActionType?();
                UserNotificationButtonActionType buttonActionType = UserNotificationButtonActionType.open_url;
                num1 = nullable.GetValueOrDefault() == buttonActionType ? (nullable.HasValue ? 1 : 0) : 0;
            }
            if (num1 != 0)
            {
                this._navigationUrl = this._button.action.url;
            }
            ((PresentationFrameworkCollection <UIElement>)((Panel)this.stackPanel).Children).Clear();
            ((FrameworkElement)this.stackPanel).Width = width;
            this._height = 0.0;
            if (this._newsfeed.layout == UserNotificationNewsfeedLayout.banner)
            {
                this.ComposeLargeUI();
            }
            else
            {
                this.ComposeSmallMediumUI();
            }
            Rectangle rectangle1 = new Rectangle();
            double    num2       = 16.0;

            ((FrameworkElement)rectangle1).Height = num2;
            SolidColorBrush solidColorBrush = (SolidColorBrush)Application.Current.Resources["PhoneNewsDividerBrush"];

            ((Shape)rectangle1).Fill = ((Brush)solidColorBrush);
            Rectangle rectangle2 = rectangle1;

            ((PresentationFrameworkCollection <UIElement>)((Panel)this.stackPanel).Children).Add((UIElement)rectangle2);
            this._height      = this._height + ((FrameworkElement)rectangle2).Height;
            this._fixedHeight = Math.Max(this._height, ((FrameworkElement)this.canvasDismiss).Height);
        }