public async Task <Notification> CreateForUser(string username, Notification notification)
        {
            var dbUser = await dbcontext.Users.FirstOrDefaultAsync(u => u.UserName == username);

            if (dbUser == null)
            {
                return(null);
            }

            var dbQuestion = await dbcontext.Questions.FirstOrDefaultAsync(q => q.Id == notification.QuestionId);

            if (dbQuestion == null)
            {
                return(null);
            }
            DbNotification dbNotification = new DbNotification
            {
                User       = dbUser,
                UserId     = dbUser.Id,
                Question   = dbQuestion,
                QuestionId = dbQuestion.Id,
                Content    = notification.Content,
                Title      = notification.Title,
            };
            var ret = await dbcontext.Notifications.AddAsync(dbNotification);

            await dbcontext.SaveChangesAsync();

            return(DbMapper.MapDbNotification(ret.Entity));
        }
        /// <summary>
        /// Gets all notifications stored in a collection as an 'object'.
        /// These notifications must NOT be mistaken as the Model class Notification.
        /// The objects can be of either Job or Project
        ///
        /// Examples on how to use this list:
        /// List<object> notifications = GetNotificationList();
        /// for (n in notifications) {
        ///     if (n is Job) {
        ///         // DO spesific Job code
        ///         Job job = (Job)n;
        ///         string date = job.expiryDate; // Will work
        ///     }
        ///     else if (n is Project) {
        ///         // Do spesific Project  code.
        ///         Project p = (Project)n;
        ///     }
        /// }
        /// </summary>
        /// <returns>A list of objects suitable for to be dislayed to the user as notifications</returns>
        public List <Advert> GetNotificationList()
        {
            DbJob                      dbJob         = new DbJob();
            DbNotification             db            = new DbNotification();
            JobsController             jc            = new JobsController();
            DbProject                  dbProject     = new DbProject();
            IEnumerable <Notification> notifications = db.GetNotifications();

            List <Advert> notificationList = new List <Advert>();

            foreach (var n in notifications)
            {
                System.Diagnostics.Debug.WriteLine("GetNotificationList: var n.id = " + n.id);
                System.Diagnostics.Debug.WriteLine("GetNotificationList: var n.jobUuid = " + n.jobUuid);
                System.Diagnostics.Debug.WriteLine("GetNotificationList: var n.projectUuid = " + n.projectUuid);

                if (!string.IsNullOrWhiteSpace(n.jobUuid))
                {
                    Job job = dbJob.GetJobByUuid(n.jobUuid);
                    job.companies = dbJob.GetAllCompaniesRelatedToJob(job);
                    notificationList.Add(job);
                }
                else
                {
                    Project project = dbProject.GetProjectByUuid(n.projectUuid);
                    project.companies = dbProject.GetAllCompaniesRelatedToProject(project);
                    notificationList.Add(project);
                }
            }
            return(notificationList.OrderByDescending(a => a.published).ToList());
        }
Exemple #3
0
        async Task SendAsync(DiscordShardedClient client, DbNotification notification)
        {
            var recipientId = notification.User.DiscordUserId;

            if (recipientId == null)
            {
                return;
            }

            // use rest to retrieve user because users are not cached in sharded clients
            var recipient = await client.Rest.GetUserAsync(recipientId.Value);

            if (recipient == null)
            {
                _logger.LogWarning($"Recipient user {recipientId} not found.");
                return;
            }

            await recipient.SendMessageAsync("", embed : new EmbedBuilder
            {
                Author = new EmbedAuthorBuilder
                {
                    Name    = notification.Title,
                    Url     = notification.Url,
                    IconUrl = notification.Icon
                },
                Description = notification.Description,

                Color = uint.TryParse(notification.Color?.TrimStart('#'), NumberStyles.HexNumber, null, out var c) ? new Color(c) : null as Color?
            }.Build());
Exemple #4
0
 private static void ManagerDB_ProcDoneHandler()
 {
     _report = DbNotification.GetResultFromDb();
     ReportUpdated?.Invoke(_report);
     if (QMediator.IsAuto)
     {
         TaskFinished?.Invoke(QMediator.CurrentTaskName);
     }
 }
Exemple #5
0
 public static Notification FromDbModel(DbNotification notification) => new Notification
 {
     Key         = notification.Key,
     Time        = notification.Time.ToUnixTimeMilliseconds(),
     Icon        = notification.Icon,
     Title       = notification.Title,
     Description = notification.Description,
     Url         = notification.Url,
     Color       = notification.Color
 };
        private async void DeleteAllNotifications(object sender, EventArgs e)
        {
            var action = await DisplayActionSheet("Slett alle varsler", "Avbryt", null, "OK");

            if (action != null && action == "OK")
            {
                DbNotification dbNotification = new DbNotification();
                dbNotification.DeleteAllNotifications();
            }
            //Sort();
            ExcecuteRefreshCommand();
        }
        public async Task UpdateStatus(Guid id, AppointmentStatus status)
        {
            var appointment = await _unitOfWork.AppointmentRepository.GetFirstOrDefaultAsync(x => x.Id == id, x => x.Patient) ?? throw new EntityNotFoundException(typeof(DbAppointment), id);

            appointment.Status = (int)status;

            string title   = "";
            string message = "";

            switch (status)
            {
            case AppointmentStatus.Cancelled:
                title   = "Huỷ lịch hẹn";
                message = $"{appointment.Patient.FirstName} {appointment.Patient.LastName} đã huỷ lịch hẹn ngày {appointment.AppointmentDate.ToString("yyyy/MM/dd HH:mm")}.";
                break;

            default:
                await _unitOfWork.CompleteAsync();

                return;
            }

            var notification = new DbNotification
            {
                UserId           = appointment.DoctorId,
                Title            = title,
                Content          = message,
                NotificationDate = DateTime.Now,
                HasRead          = false,
                Image            = appointment.Patient.ImageProfile,
                AppointmentId    = appointment.Id
            };
            await _unitOfWork.NotificationRepository.AddAsync(notification).ContinueWith(x => _unitOfWork.Complete());

            await _pushNotificationService.SendToAllDeviceUsers(appointment.DoctorId, new FcmPayloadNotification
            {
                Notification = new FcmNotification
                {
                    Title = notification.Title,
                    Body  = notification.Content
                },
                Data = new FcmDataNotification
                {
                    Id               = notification.Id.ToString(),
                    Image            = notification.Image,
                    NotificationDate = notification.NotificationDate.ToString("yyyy-MM-ddTHH:mm:ssZ"),
                    AppointmentId    = appointment.Id.ToString()
                }
            });

            await _unitOfWork.CompleteAsync();
        }
        private async Task <bool> CreateNotificationEmailsAsync(DbEnrollment enrollment)
        {
            var user      = enrollment.User;
            var course    = enrollment.Course;
            var studyDate = enrollment.StudyDate;


            var notificationDays = new DateTime[] {
                studyDate.AddMonths(-1),
                studyDate.AddDays(-7),
                studyDate.AddDays(-1)
            };

            var body = await emailService.GetNotificationTemplateAsync(course.Name, studyDate.GetDaysToStudy());

            if (body == null)
            {
                return(false);
            }

            BackgroundJob.Enqueue(() => emailService.SendEmail(user.Email, "Notification", body));

            for (int i = 0; i < notificationDays.Length; i++)
            {
                if (notificationDays[i] > DateTime.UtcNow)
                {
                    var arrayDate = new int[] { 30, 7, 1 };
                    body = await emailService.GetNotificationTemplateAsync(course.Name, arrayDate[i]);

                    if (body == null)
                    {
                        return(false);
                    }

                    var jobId = BackgroundJob.Schedule(
                        () => emailService.SendEmail(user.Email, "Notification", body),
                        notificationDays[i]);

                    DbNotification notification = new DbNotification
                    {
                        EnrollmentId  = enrollment.Id,
                        HangfireJobId = jobId
                    };

                    context.Notifications.Add(notification);
                    context.SaveChanges();
                }
            }
            return(true);
        }
        private void DeleteNotification(Varsel varsel)
        {
            varsler.Remove(varsel);
            DbNotification dbNotification = new DbNotification();

            if (varsel.Type == "job")
            {
                dbNotification.DeleteNotificationBasedOnJob(varsel.Uuid);
            }
            else
            {
                dbNotification.DeleteNotificationBasedOnProject(varsel.Uuid);
            }
        }
        public async Task <Notification> CreateWithUserId(string userId, Notification notification)
        {
            DbNotification dbNotification = new DbNotification
            {
                UserId     = userId,
                QuestionId = notification.QuestionId,
                Content    = notification.Content,
                Title      = notification.Title,
            };
            var ret = await dbcontext.Notifications.AddAsync(dbNotification);

            await dbcontext.SaveChangesAsync();

            return(DbMapper.MapDbNotification(ret.Entity));
        }
        /// <summary>
        /// Receives a Message from GCM. The method exctracts a message from the Bundle data,
        /// and calls SendNotification.
        ///
        /// If the students have enabled receiveNotifications, but
        /// disabled receiveProjectNotifications and receiveJobNotifications
        /// The student can still receive more general messages sent as push notifications
        /// however these notifications will only be displayed once and won't be displayed in the
        /// notification list.
        /// </summary>
        public override async void OnMessageReceived(string from, Bundle data)
        {
            DbStudent dbStudent = new DbStudent();
            var       message   = data.GetString("message");

            Log.Debug("MyGcmListenerService", "From:    " + from);
            Log.Debug("MyGcmListenerService", "Message: " + message);
            var     type    = data.GetString("type");
            var     uuid    = data.GetString("uuid");
            Student student = dbStudent.GetStudent();

            if (student != null && student.receiveNotifications)
            {
                DbNotification dbNotification = new DbNotification();
                if (type == "project")
                {
                    if (student.receiveProjectNotifications)
                    {
                        SendNotification(message);
                        Log.Debug("MyGcmListenerService", "type: " + type);
                        Log.Debug("MyGcmListenerService", "uuid: " + uuid);
                        // type = job or project

                        Log.Debug("MyGcmListenerService", "After New NotificationController, but before use of method.");
                        dbNotification.InsertNotification(type, uuid);
                    }
                }
                else if (type == "job")
                {
                    if (student.receiveJobNotifications)
                    {
                        SendNotification(message);
                        Log.Debug("MyGcmListenerService", "type: " + type);
                        Log.Debug("MyGcmListenerService", "uuid: " + uuid);
                        // type = job or project

                        Log.Debug("MyGcmListenerService", "After New NotificationController, but before use of method.");
                        dbNotification.InsertNotification(type, uuid);
                    }
                }
                else
                {
                    SendNotification(message);
                }
            }
        }
Exemple #12
0
 internal static Notification MapDbNotification(DbNotification dbNotification)
 {
     if (dbNotification == null)
     {
         return(null);
     }
     return(new Notification()
     {
         Id = dbNotification.Id,
         Title = dbNotification.Title,
         Content = dbNotification.Content,
         QuestionId = dbNotification.QuestionId,
         Seen = dbNotification.Seen,
         Important = dbNotification.Important,
         Username = dbNotification.User?.UserName,
     });
 }
Exemple #13
0
        public static void ToArchive()
        {
            try
            {
                QMediator.CurrentTaskName = TaskName.MoveToArc;
                DbNotification.ResultWaiter();

                using (OracleCommand cmd = new OracleCommand("reg_upload.move_arc_and_lpd", _con))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.ExecuteNonQuery();
                }
            }
            catch (Exception ex)
            {
                ExceptionHandler("ToArchive()", ex.Message);
            }
        }
Exemple #14
0
        public static void StatusR()
        {
            try
            {
                QMediator.CurrentTaskName = TaskName.StateR;
                DbNotification.ResultWaiter();

                using (OracleCommand cmd = new OracleCommand("reg_upload.set_r_status_loop", _con))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.ExecuteNonQuery();
                }
            }
            catch (Exception ex)
            {
                ExceptionHandler("StatusR()", ex.Message);
            }
        }
Exemple #15
0
        public static void ChangeCurrency()
        {
            try
            {
                QMediator.CurrentTaskName = TaskName.CurrChange;
                DbNotification.ResultWaiter();

                using (OracleCommand cmd = new OracleCommand("reg_upload.ccy_update", _con))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.ExecuteNonQuery();
                }
            }
            catch (Exception ex)
            {
                ExceptionHandler("ChangeCurrency()", ex.Message);
            }
        }
Exemple #16
0
        public static void FinishCheck()
        {
            try
            {
                QMediator.CurrentTaskName = TaskName.FinishCheck;
                DbNotification.ResultWaiter();

                using (OracleCommand cmd = new OracleCommand("reg_upload.finish_check", _con))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.ExecuteNonQuery();
                }
            }
            catch (Exception ex)
            {
                ExceptionHandler("FinishCheck()", ex.Message);
            }
        }
Exemple #17
0
        public static void RegInit(string regName)
        {
            try
            {
                DbNotification.ResultWaiter();

                using (OracleCommand cmd = new OracleCommand("reg_upload.initRegNew", _con))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("regLongName", OracleDbType.Varchar2).Value = regName;
                    cmd.ExecuteNonQuery();
                }
            }
            catch (Exception ex)
            {
                ExceptionHandler("RegInit()", ex.Message);
            }
            RegInitialized?.Invoke(true);
        }
        public async Task <Appointment> AddAppointmentAsync(Guid userId, CreatedAppointment model)
        {
            var appointment = _mapper.Map <DbAppointment>(model);

            appointment.Status    = (int)AppointmentStatus.Confirming;
            appointment.PatientId = userId;

            var addedAppointment = await _unitOfWork.AppointmentRepository.AddAsync(appointment);

            await _unitOfWork.CompleteAsync();

            var appointmentDb = await _unitOfWork.AppointmentRepository.GetFirstOrDefaultAsync(x => x.Id == addedAppointment.Id, x => x.Patient) ?? throw new EntityNotFoundException(typeof(DbAppointment), addedAppointment.Id);

            var notification = new DbNotification
            {
                UserId           = addedAppointment.DoctorId,
                Title            = "Có lịch hẹn mới",
                Content          = $"Bạn có lịch hẹn mới với {appointmentDb.Patient.FirstName} {appointmentDb.Patient.LastName} vào lúc {addedAppointment.AppointmentDate.ToString("HH:mm dd/MM/yyyy")}. Xem chi tiết.",
                NotificationDate = DateTime.Now,
                HasRead          = false,
                Image            = appointment.Patient.ImageProfile,
                AppointmentId    = appointment.Id
            };
            await _unitOfWork.NotificationRepository.AddAsync(notification).ContinueWith(x => _unitOfWork.Complete());

            await _pushNotificationService.SendToAllDeviceUsers(appointment.DoctorId, new FcmPayloadNotification
            {
                Notification = new FcmNotification
                {
                    Title = notification.Title,
                    Body  = notification.Content
                },
                Data = new FcmDataNotification
                {
                    Id               = notification.Id.ToString(),
                    Image            = notification.Image,
                    NotificationDate = notification.NotificationDate.ToString("yyyy-MM-ddTHH:mm:ssZ"),
                    AppointmentId    = appointment.Id.ToString()
                }
            });

            return(await GetAppointmentAsync(addedAppointment.Id));
        }
Exemple #19
0
        public static void PreCheck(string count)
        {
            try
            {
                DbNotification.ProcDoneHandler += ManagerDB_ProcDoneHandler;
                DbNotification.ResultWaiter();

                using (OracleCommand cmd = new OracleCommand("reg_upload.first_check", _con))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("count_of_deals", OracleDbType.Int32).Value = Convert.ToInt32(count);
                    cmd.ExecuteNonQuery();
                }
            }
            catch (Exception ex)
            {
                ExceptionHandler("PreCheck()", ex.Message);
            }
        }
Exemple #20
0
        async Task SendAsync(IDiscordClient client, DbNotification notification)
        {
            var recipient = await client.GetUserAsync(notification.User.DiscordUserId ?? 0);

            if (recipient == null)
            {
                _logger.LogWarning($"No recipient user {notification.User.DiscordUserId?.ToString() ?? "<null>"} found.");
                return;
            }

            string fixUrl(string url)
            => Uri.TryCreate(_defaultBaseUri, url, out var uri) ? uri.AbsoluteUri : null;

            await recipient.SendMessageAsync("", embed : new EmbedBuilder
            {
                ThumbnailUrl = fixUrl(notification.Icon),
                Title        = notification.Title,
                Description  = notification.Description,
                Url          = fixUrl(notification.Url),
                Color        = uint.TryParse(notification.Color?.TrimStart('#'), NumberStyles.HexNumber, null, out var c) ? new Color(c) : null as Color?
            }.Build());
        public List <object> GetNotificationListJobOnly()
        {
            DbJob                      dbJob         = new DbJob();
            DbNotification             db            = new DbNotification();
            IEnumerable <Notification> notifications = db.GetNotifications();

            List <object> notificationList = new List <object>();

            foreach (var n in notifications)
            {
                System.Diagnostics.Debug.WriteLine("GetNotificationList: var n.id = " + n.id);
                System.Diagnostics.Debug.WriteLine("GetNotificationList: var n.jobUuid = " + n.jobUuid);
                if (!string.IsNullOrWhiteSpace(n.jobUuid))
                {
                    Job job = dbJob.GetJobByUuid(n.jobUuid);
                    job.companies = dbJob.GetAllCompaniesRelatedToJob(job);
                    notificationList.Add(job);
                }
            }
            return(notificationList);
        }
        public async Task <ActionResult> PutAsync(string key, Notification model)
        {
            var userId = HttpContext.GetUserId();

            try
            {
                var notification = await _db.Notifications.AsTracking().FirstOrDefaultAsync(n => n.User.Id == userId && n.Key == key);

                if (notification == null)
                {
                    await _db.Notifications.AddAsync(notification = new DbNotification());
                }

                notification.User = _db.Users.Attach(new DbUser {
                    Id = userId
                }).Entity;

                notification.Key         = key;
                notification.Time        = DateTimeOffset.FromUnixTimeMilliseconds(model.Time);
                notification.Icon        = model.Icon;
                notification.Title       = model.Title;
                notification.Description = model.Description;
                notification.Url         = model.Url;
                notification.Color       = model.Color;

                await _db.SaveChangesAsync();

                _actions.Labels("set").Inc();

                return(Ok($"Notification '{key}' updated."));
            }
            catch (Exception e)
            {
                var message = $"Could not update notification '{key}' for user {userId}.";

                _logger.LogWarning(e, message);

                return(StatusCode(500, message));
            }
        }
        public List <object> GetNotificationListProjectOnly()
        {
            DbNotification             db               = new DbNotification();
            DbProject                  dbProject        = new DbProject();
            IEnumerable <Notification> notifications    = db.GetNotifications();
            List <object>              notificationList = new List <object>();

            foreach (var n in notifications)
            {
                System.Diagnostics.Debug.WriteLine("GetNotificationList: var n.id = " + n.id);
                System.Diagnostics.Debug.WriteLine("GetNotificationList: var n.jobUuid = " + n.jobUuid);
                System.Diagnostics.Debug.WriteLine("GetNotificationList: var n.projectUuid = " + n.projectUuid);

                if (!string.IsNullOrWhiteSpace(n.projectUuid))
                {
                    Project project = dbProject.GetProjectByUuid(n.projectUuid);
                    project.companies = dbProject.GetAllCompaniesRelatedToProject(project);
                    notificationList.Add(project);
                }
            }
            return(notificationList);
        }
Exemple #24
0
        public static void ProgsToExec(ExecProgsType taskName)
        {
            try
            {
                _report = "Выполнение программ...\n\n";
                ReportUpdated?.Invoke(_report);
                if (QMediator.PathToProgDest != null)
                {
                    string str;
                    if (taskName == ExecProgsType.Oktel)
                    {
                        str = "\\post!\\oktel";
                        QMediator.CurrentTaskName = TaskName.Oktel;
                        DbNotification.ResultWaiter();
                    }
                    else
                    {
                        str = taskName == ExecProgsType.PredProgs ? "\\!pred" : "\\post!";
                    }

                    string path = QMediator.PathToProgDest + str;
                    if (!new DirectoryInfo(path).Exists)
                    {
                        Directory.CreateDirectory(path);
                        _report = "Нет программ для выполнения.";
                    }
                    else
                    {
                        List <string> filePathList = GetFilesForExec(path);
                        if (filePathList.Count < 1)
                        {
                            _report = "Нет программ для выполнения.";
                            ReportUpdated?.Invoke(_report);

                            if (taskName == ExecProgsType.PredProgs)
                            {
                                TaskFinished?.Invoke(TaskName.PredProgs);
                            }
                            else if (taskName == ExecProgsType.PostProgs)
                            {
                                TaskFinished?.Invoke(TaskName.PostProgs);
                            }
                            else
                            {
                                TaskFinished?.Invoke(TaskName.Oktel);
                            }

                            return;
                        }
                        foreach (var item in filePathList)
                        {
                            _report += Environment.NewLine + "Файл:\t\t" + item;
                            bool   isOk     = true;
                            string fileText = File.ReadAllText(item, Encoding.Default);
                            try
                            {
                                if (fileText.ToLower().Contains("begin"))
                                {
                                    ManagerDB.ExecCommand(fileText);
                                }
                                else
                                {
                                    isOk = SplitAndExec(fileText);
                                }
                            }
                            catch (Exception ex)
                            {
                                isOk = false;
                                ExceptionHandler("ProgsToExec()", ex.Message);
                            }
                            _report += ("\t" + (isOk == true ? "отработал нормально." : "отработал с ошибками.") + Environment.NewLine);
                        }
                    }
                }
                else
                {
                    _report = "Не определен путь к программам.";
                }

                ReportUpdated?.Invoke(_report);
                if (taskName == ExecProgsType.PredProgs)
                {
                    TaskFinished?.Invoke(TaskName.PredProgs);
                }
                else if (taskName == ExecProgsType.PostProgs)
                {
                    TaskFinished?.Invoke(TaskName.PostProgs);
                }
                else
                {
                    TaskFinished?.Invoke(TaskName.Oktel);
                }
            }
            catch (Exception ex)
            {
                ExceptionHandler("ProgsToExec()", ex.Message);
            }
        }