public object DoWork(object state)
        {
            EntityQuery2 q = new EntityQuery2(Notification.ENTITY);
            q.WhereIs("Method", ReplyMethods.ByEmail);
            q.WhereIs("EmailSent", false);
            q.WhereLessThen("EmailRetries", 6);
            q.Paging = new Paging(1, 5);
            q.Include(User.ENTITY, Roles.Recipient);
            q.Include(File.ENTITY, Roles.Attachment);
            q.AllProperties = true;
            var pending = _repository.Search(q).Select(e => new Notification(e));
            foreach (var notif in pending)
            {
                try
                {
                    _notificationService.SendEmail(notif.Recipient.Email, notif.Subject, notif.Body, notif.Attachments);
                }
                catch (Exception)
                {
                    _repository.Update(new Notification(notif.Id) { EmailRetries = notif.EmailRetries + 1 });
                    continue;
                }
                var upd = new Notification(notif.Id) { EmailSent = true };
                _repository.Update(upd);
            }

            return state;
        }
        public void SendNotification(bool withEmail, IEnumerable<User> to, string subject, string body, IEnumerable<Domain.File> attachments, IEnumerable<Relation> relations = null)
        {
            using (var dbContext = _dbService.GetDatabaseContext(true))
            {
                foreach (var user in to)
                {
                    Notification notif = new Notification()
                    {
                        Subject = subject,
                        Body = body,
                        Date = DateTime.Now,
                        Method = withEmail ? ReplyMethods.ByEmail : ReplyMethods.ByNotification
                    };

                    _repository.Create(notif);
                    _repository.Attach(notif, new Relation(Roles.Recipient, user));
                    _repository.Attach(notif, new Relation(Roles.Sender, _securityService.CurrentUser));
                    if (attachments != null)
                    {
                        foreach (var file in attachments)
                        {
                            _repository.Attach(notif, new Relation(Roles.Attachment, file));
                            _fileService.GrantAccess(file.Id, FileAccessType.Read, user);
                        }
                    }
                    if (relations != null)
                        foreach (var rel in relations)
                        {
                            var relToSave = new Relation(rel.Role, rel.Entity);
                            relToSave.Data = new Dictionary<string, object>(rel.Data);
                            _repository.Attach(notif, relToSave);
                        }
                }
                dbContext.Complete();
            }
        }