public bool AddNotification(TaskNotification notification) { _inAppNotificationEntities.TaskNotifications.Add(notification); var response = _inAppNotificationEntities.SaveChanges(); return(response > 0); }
public void CloseIdle() { if (!IsRunning()) { return; } TimeSpan idleTime = new TimeSpan(_taskData.ActioningData.StopIfIdleHours, _taskData.ActioningData.StopIfIdleMinutes, _taskData.ActioningData.StopIfIdleSeconds); if (idleTime.TotalSeconds == 0) { return; // Do not kill tasks with 0 idle hours, minutes, seconds. } if (_taskData.DebugData.DateLastSignal.Add(idleTime) < DateTime.Now) { DoKill(); _taskData.DebugData.TaskStatus = ETaskStatus.Ready; StatusChanged?.Invoke(this, new TaskStatusChangedEventArgs(_taskStatus, _taskData.Id)); const string notificationMessageTemplate = "Task \"{0}\" stopped after being idle"; string notificationMessage = string.Format(notificationMessageTemplate, _taskData.Name); TaskNotification?.Invoke(this, new TaskNotificationEventArgs(notificationMessage, _taskData.Id, _taskData.Name, ENotificationType.TaskIdleKilled)); string managementMessage = ToManagementMessage(notificationMessage); _taskData.DebugData.Output += managementMessage; ManagementDataReceived?.Invoke(this, new TaskDataReceivedEventArgs(managementMessage, _taskData.Id)); } }
public void ShowNotification(TaskNotification notification) { //This avoid replacing an existing notification if (notification.Id == 0) { notification.Id = (int)DateTime.Now.Ticks; } var builder = BuildSimpleNotification(notification); var notif = builder.Build(); NotifManager.Notify(notification.Id, notif); }
private void FireTaskNotification(object sender, TaskNotificationEventArgs e) { if (InvokeRequired) { FireTaskNotificationCallback d = new FireTaskNotificationCallback(FireTaskNotification); this?.Invoke(d, new object[] { sender, e }); } else { TaskNotification?.Invoke(sender, e); } }
public void Kill() { DoKill(); const string notificationMessageTemplate = "Task \"{0}\" killed."; string notificationMessage = string.Format(notificationMessageTemplate, _taskData.Name); TaskNotification?.Invoke(this, new TaskNotificationEventArgs(notificationMessage, _taskData.Id, _taskData.Name, ENotificationType.TaskKilled)); string managementMessage = ToManagementMessage(notificationMessage); _taskData.DebugData.Output += managementMessage; ManagementDataReceived?.Invoke(this, new TaskDataReceivedEventArgs(managementMessage, _taskData.Id)); }
public void ShowTaskReminderNotification(TaskReminderNotification notification) { //we create the pending intent when the user clicks the notification... var action = new NotificationAction { Action = NotificationActionType.OPEN_TASK, TaskId = notification.TaskId, TaskListId = notification.TaskListId }; var clickIntent = MainActivity.CreateIntent( notification.Id, MainActivity.InitParamsKey, JsonConvert.SerializeObject(action)); var pendingIntent = TaskStackBuilder.Create(Application.Context) .AddNextIntent(clickIntent) .GetPendingIntent(1, (int)PendingIntentFlags.UpdateCurrent); var localNotification = new TaskNotification { LargeContent = $"{notification.TaskTitle}{System.Environment.NewLine}" + $"{notification.TaskBody}", Title = notification.TaskListTitle, Id = notification.Id }; var builder = BuildSimpleNotification(localNotification); builder.SetContentIntent(pendingIntent); //we create the pending intent when the user clicks the mark as completed button... var mcIntent = MarkTaskAsCompletedReceiver.CreateIntent( notification.Id, MarkTaskAsCompletedReceiver.MarkTaskAsCompletedKey, JsonConvert.SerializeObject(notification)); var mcPendingIntent = PendingIntent.GetBroadcast( Application.Context, 0, mcIntent, 0); string title = _textProvider.Get("MarkTaskAs", _textProvider.Get("Completed")); builder.AddAction(Resource.Drawable.ic_check_white_48dp, title, mcPendingIntent); var notif = builder.Build(); NotifManager.Notify(notification.Id, notif); }
private NotificationCompat.Builder BuildSimpleNotification(TaskNotification notification) { var pendingIntent = GetIntentToMainActivity(notification.Id); var builder = BuildSimpleNotification(notification.Title, notification.Content) .SetAutoCancel(true) .SetContentIntent(pendingIntent); if (!string.IsNullOrEmpty(notification.LargeContent)) { builder.SetStyle(new NotificationCompat.BigTextStyle().BigText(notification.LargeContent)); } return(builder); }
public void ShowNotification(TaskNotification notification) { var content = GenerateSimpleToastContent( notification.Title, notification.Content, notification.UwpSettings?.ShowDismissButton ?? true, notification.UwpSettings?.IsAudioSilent ?? false); var toastNotifcation = new ToastNotification(content.GetXml()); if (!string.IsNullOrEmpty(notification.UwpSettings?.Tag)) { toastNotifcation.Tag = notification.UwpSettings.Tag; } ShowToastNotification(toastNotifcation); }
private async Task NotifyUser(int id)//TaskId { TasksViewModel vmTasks = _TaskService.FindViewModel(id); Notification objNotification = new Notification(); objNotification.NotificationSubjectId = (int)NotificationSubjectConstants.TaskCreated; objNotification.CreatedBy = User.Identity.Name; objNotification.CreatedDate = DateTime.Now; objNotification.ExpiryDate = DateTime.Now.AddDays(7); objNotification.IsActive = true; objNotification.ModifiedBy = User.Identity.Name; objNotification.ModifiedDate = DateTime.Now; objNotification.NotificationUrl = "/Tasks/Index?SiteId=16&DivisionId=6"; objNotification.UrlKey = "TaskDomain"; objNotification.NotificationText = vmTasks.TaskTitle; TaskNotification nc = new TaskNotification(); await nc.CreateTaskNotificationAsync(objNotification, vmTasks.ForUser); }
public async Task Initialize() { DateTime lastestStartupDate; DateTime.TryParseExact(await DataManager.Current.GetValueAsync("latestStartupDate"), "yyyy-MM-dd", null, System.Globalization.DateTimeStyles.None, out lastestStartupDate); BackgroundServiceRunArgs = new AppServiceRunArgs(this, lastestStartupDate); //Services start up Cleaner.Start(BackgroundServiceRunArgs);//Always Run First WeatherUpdate.Start(BackgroundServiceRunArgs); TaskNotification.Start(BackgroundServiceRunArgs); //Timer starts up DateTime now = DateTime.Now; await Task.Delay((int)checked (60000 - now.Ticks / 10000 % 60000)); timer.Start(); //TimeLoop(timer, new EventArgs()); }
public async Task NotifyUser(int id)//TaskId { DocumentTypeTimeExtension Temp = db.DocumentTypeTimeExtension.Find(id); db.Entry <DocumentTypeTimeExtension>(Temp).Reference(m => m.DocType).Load(); Notification NN = new Notification(); NN.NotificationSubjectId = (int)NotificationSubjectConstants.PermissionAssigned; NN.CreatedBy = User.Identity.Name; NN.CreatedDate = DateTime.Now; NN.ExpiryDate = DateTime.Now.AddDays(1); NN.IsActive = true; NN.ModifiedBy = User.Identity.Name; NN.ModifiedDate = DateTime.Now; NN.NotificationText = "Permission assigned for " + Temp.DocType.DocumentTypeName + " dated " + Temp.DocDate.ToString("dd/MMM/yyyy"); TaskNotification nc = new TaskNotification(); await nc.CreateTaskNotificationAsync(NN, Temp.UserName); }
private void Process_ErrorDataReceived(object sender, System.Diagnostics.DataReceivedEventArgs e) { lock (_locker) { _taskData.DebugData.DateLastSignal = DateTime.Now; if (!string.IsNullOrEmpty(e.Data)) { _hasErrorMessage = true; } if (_hasErrorMessage) { string message = ToErrorMessage(e.Data); _taskData.DebugData.Output += message; ErrorDataReceived?.Invoke(this, new TaskDataReceivedEventArgs(message, _taskData.Id)); _taskData.DebugData.TaskStatus = ETaskStatus.RunningWithErrors; _taskStatus = _taskData.DebugData.TaskStatus; StatusChanged?.Invoke(this, new TaskStatusChangedEventArgs(_taskStatus, _taskData.Id)); const string notificationMessageTemplate = "Task \"{0}\" sent error message:\r\n\t {1}."; string notificationMessage = string.Format(notificationMessageTemplate, _taskData.Name, e.Data); TaskNotification?.Invoke(this, new TaskNotificationEventArgs(notificationMessage, _taskData.Id, _taskData.Name, ENotificationType.TaskError)); } } }
private void Process_OutputDataReceived(object sender, System.Diagnostics.DataReceivedEventArgs e) { lock (_locker) { _taskData.DebugData.DateLastSignal = DateTime.Now; if (!string.IsNullOrEmpty(e.Data)) { _hasOutputMessage = true; } if (_hasOutputMessage) { string message = ToOutputMessage(e.Data); _taskData.DebugData.Output += message; OutputDataReceived?.Invoke(this, new TaskDataReceivedEventArgs(message, _taskData.Id)); if (_taskData.NotifyProgressOutput) { const string notificationMessageTemplate = "Task \"{0}\" sent normal progress message:\r\n\t {1}."; string notificationMessage = string.Format(notificationMessageTemplate, _taskData.Name, e.Data); TaskNotification?.Invoke(this, new TaskNotificationEventArgs(notificationMessage, _taskData.Id, _taskData.Name, ENotificationType.TaskOutput)); } } } }
private void Process_Exited(object sender, EventArgs e) { lock (_locker) { _taskData.DebugData.DateLastSignal = DateTime.Now; Process process = sender as Process; int result = process.ExitCode; //this tell if there was an error or not string message = ToExitMessage(result.ToString()); _taskData.DebugData.Output += message; Exited?.Invoke(this, new TaskExitedEventArgs(result, message, _taskData.Id)); _taskData.DebugData.TaskStatus = _taskData.DebugData.HasErrors()?ETaskStatus.CompletedWithErrors: ETaskStatus.Ready; _taskStatus = _taskData.DebugData.TaskStatus; StatusChanged?.Invoke(this, new TaskStatusChangedEventArgs(_taskStatus, _taskData.Id)); _hasErrorMessage = false; _hasOutputMessage = false; _process = null; const string notificationMessageTemplate = "Task \"{0}\" exited with exit code {1}."; string notificationMessage = string.Format(notificationMessageTemplate, _taskData.Name, process.ExitCode); TaskNotification?.Invoke(this, new TaskNotificationEventArgs(notificationMessage, _taskData.Id, _taskData.Name, ENotificationType.TaskExit)); string managementMessage = ToManagementMessage(notificationMessage); _taskData.DebugData.Output += managementMessage; ManagementDataReceived?.Invoke(this, new TaskDataReceivedEventArgs(managementMessage, _taskData.Id)); } }
public async Task CreateTaskNotification(MTask task, ApplicationUser author, TaskNotificationType type, Company company) { HashSet <string> users = new HashSet <string>(); var newNotification = new TaskNotification(); newNotification.Author = author; newNotification.Task = task; newNotification.Type = type; newNotification.DateTime = DateTime.Now; await _context.TaskNotifications.AddAsync(newNotification); await _context.SaveChangesAsync(); if (task.CoExecutors != null) { foreach (var coExecutor in task.CoExecutors) { // Проверяем что для указаного сотрудника еще не было // сформированно уведомление if (!users.Contains(coExecutor.Id)) { var taskNotificationEmployee = CreateNotificationEmployee(newNotification.TaskNotificationId, coExecutor.Id, company.CompanyId); await _context.TaskNotificationEmployees.AddAsync(taskNotificationEmployee); // заносим указаного сотрудника в список // сотрудников которым было сформированно уведомление users.Add(coExecutor.Id); } } } if (task.Observers != null) { foreach (var observer in task.Observers) { if (!users.Contains(observer.Id)) { var taskNotificationEmployee = CreateNotificationEmployee(newNotification.TaskNotificationId, observer.Id, company.CompanyId); await _context.TaskNotificationEmployees.AddAsync(taskNotificationEmployee); users.Add(observer.Id); } } } if (task.ResponsiblesForExecution != null) { foreach (var responsibleForExecution in task.ResponsiblesForExecution) { if (!users.Contains(responsibleForExecution.Id)) { var taskNotificationEmployee = CreateNotificationEmployee(newNotification.TaskNotificationId, responsibleForExecution.Id, company.CompanyId); await _context.TaskNotificationEmployees.AddAsync(taskNotificationEmployee); users.Add(responsibleForExecution.Id); } } } if (task.Author != null && !users.Contains(task.Author.Id)) { var taskNotificationEmployee = CreateNotificationEmployee(newNotification.TaskNotificationId, task.Author.Id, company.CompanyId); await _context.TaskNotificationEmployees.AddAsync(taskNotificationEmployee); } }
public async Task Sync() { try { _logger.Information( $"{nameof(Sync)}: Started {(_startedManually ? "manually" : "automatically")}"); bool isSyncServiceRunning = (_appSettings as IAndroidAppSettings) .GetBoolean(SyncBackgroundService.IsServiceRunningKey); if (!_startedManually && isSyncServiceRunning) { _logger.Warning($"{nameof(Sync)}: The sync bg service is already running..."); return; } string msg = $"{_textProvider.Get("Syncing")}..."; await _dispatcher.ExecuteOnMainThreadAsync(() => _messenger.Publish(new ShowProgressOverlayMsg(this, msg: msg))); if (!_networkService.IsInternetAvailable()) { _logger.Warning($"{nameof(Sync)}: Network is not available..."); msg = _textProvider.Get("NetworkNotAvailable"); await _dispatcher.ExecuteOnMainThreadAsync(() => _messenger.Publish(new ShowProgressOverlayMsg(this, false, msg))); return; } bool syncOnlyOneTaskList = _taskListId.HasValue; if (syncOnlyOneTaskList) { _logger.Information($"{nameof(Sync)}: We will perform a partial sync for the " + $"tasklistId = {_taskListId.Value} and its associated tasks"); } else { _logger.Information($"{nameof(Sync)}: We will perform a full sync"); } var syncResults = !syncOnlyOneTaskList ? await _syncService.PerformFullSync(true) : await _syncService.PerformSyncOnlyOn(_taskListId.Value); if (syncResults.Any(r => !r.Succeed)) { var errors = string.Join( $".{Environment.NewLine}", syncResults .Where(r => !r.Succeed) .Select(r => r.Message) .Distinct()); _logger.Error($"{nameof(Sync)}: Sync completed with errors = {errors}"); } string message = syncResults.Any(r => !r.Succeed) ? _textProvider.Get("SyncUnknownError") : !_startedManually ? _textProvider.Get("SyncAutoCompleted") : _textProvider.Get("SyncManualCompleted"); if (string.IsNullOrEmpty(message)) { message = "An unknown error occurred while trying to perform the sync operation."; } _logger.Information($"{nameof(Sync)}: results = {message}"); await _dispatcher.ExecuteOnMainThreadAsync(() => _messenger.Publish(new ShowProgressOverlayMsg(this, false))); bool isInForeground = AndroidUtils.IsAppInForeground(); if (!isInForeground && _appSettings.ShowToastNotificationAfterFullSync) { _logger.Information($"{nameof(Sync)}: App is not in foreground, showing a notification..."); var notif = new TaskNotification { Content = message, Title = _textProvider.Get("SyncResults") }; _notificationService.ShowNotification(notif); } else if (isInForeground) { _logger.Information($"{nameof(Sync)}: App is in foreground, showing the snackbar msg..."); await _dispatcher.ExecuteOnMainThreadAsync(() => { _dialogService.ShowSnackBar(message); _messenger.Publish(new OnFullSyncMsg(this)); }); } _logger.Information($"{nameof(Sync)}: completed successfully"); } catch (Exception e) { _logger?.Error(e, $"{nameof(Sync)}: An unknown error occurred while trying to sync task / tasklists"); _telemetryService?.TrackError(e); } }
private void RunTaskAsProcess(TaskData taskData) { _hasErrorMessage = false; _hasOutputMessage = false; var process = new Process { StartInfo = new ProcessStartInfo { FileName = taskData.ActioningData.Command, Arguments = taskData.ActioningData.Parameters, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, WorkingDirectory = taskData.ActioningData.StartIn, CreateNoWindow = true } }; if (taskData.ActioningData.RunAsOther) { System.Security.SecureString ssPwd = new System.Security.SecureString(); process.StartInfo.Domain = taskData.ActioningData.Domain; process.StartInfo.UserName = taskData.ActioningData.UserName; string password = taskData.ActioningData.Password; for (int x = 0; x < password.Length; x++) { ssPwd.AppendChar(password[x]); } process.StartInfo.Password = ssPwd; } process.OutputDataReceived += Process_OutputDataReceived; process.ErrorDataReceived += Process_ErrorDataReceived; process.EnableRaisingEvents = true; process.Exited += Process_Exited; _taskData.DebugData.Output = string.Empty; _taskData.DebugData.TaskStatus = ETaskStatus.Running; _taskStatus = _taskData.DebugData.TaskStatus; string notificationMessageTemplate = "Starting task \"{0}\"... "; string notificationMessage = string.Format(notificationMessageTemplate, _taskData.Name); TaskNotification?.Invoke(this, new TaskNotificationEventArgs(notificationMessage, _taskData.Id, _taskData.Name, ENotificationType.TaskStart)); string managementMessage = ToManagementMessage(notificationMessage); _taskData.DebugData.Output += managementMessage; ManagementDataReceived?.Invoke(this, new TaskDataReceivedEventArgs(managementMessage, _taskData.Id)); StatusChanged?.Invoke(this, new TaskStatusChangedEventArgs(_taskStatus, _taskData.Id)); _taskData.DebugData.DateStarted = DateTime.Now; try { process.Start(); } catch (Exception ex) { notificationMessageTemplate = "Error while running \"{0}\": \r\b\t:{1}"; notificationMessage = string.Format(notificationMessageTemplate, _taskData.Name, ex.Message); TaskNotification?.Invoke(this, new TaskNotificationEventArgs(notificationMessage, _taskData.Id, _taskData.Name, ENotificationType.TaskCrash)); managementMessage = ToManagementMessage(notificationMessage); _taskData.DebugData.Output += managementMessage; ManagementDataReceived?.Invoke(this, new TaskDataReceivedEventArgs(managementMessage, _taskData.Id)); } process.BeginOutputReadLine(); process.BeginErrorReadLine(); _process = process; }
public NotificationSchedulerTask(TaskNotification notification) : this() { _notification = notification; }