public async Task <IActionResult> ProcessNotification(NotificationDTO notificationDTO)
        {
            if (!ModelState.IsValid || notificationDTO == null)
            {
                return(BadRequest("The body of request is not valid"));
            }

            if (!int.TryParse(notificationDTO.Id, out int notificationid))
            {
                return(BadRequest("Cannot parse notification id."));
            }

            if (!int.TryParse(notificationDTO.UserId, out int userId))
            {
                return(BadRequest("Cannot parse user id."));
            }

            bool isNotificationAccepted = notificationDTO.Action;

            try
            {
                await _repository.Process(notificationid, isNotificationAccepted, userId).ConfigureAwait(true);
            }
            catch (ArgumentException ex)
            {
                return(BadRequest(ex.Message));
            }

            return(Ok());
        }
示例#2
0
        public async Task <IHttpActionResult> PostNotification(Notification notification)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            notification.CreatedAt = DateTime.Now;
            db.Notifications.Add(notification);
            await db.SaveChangesAsync();

            var notificationDto = new NotificationDTO()
            {
                Id                = notification.Id,
                Action            = notification.Action,
                Source            = notification.Source,
                UserId            = notification.UserId,
                Type              = notification.Type,
                CallToAction      = notification.CallToAction,
                CallToActionLink  = notification.CallToActionLink,
                IsRead            = notification.IsRead,
                AdditionalMessage = notification.AdditionalMessage,
                CreatedAt         = notification.CreatedAt
            };

            return(Ok(notificationDto));
        }
        public async Task <HttpResponseMessage> CreateNotifications(NotificationDTO notify)
        {
            HttpResponseMessage responce;

            try
            {
                notify = await _notificationDataService.CreateNotification(notify);

                _logger.Info($"SendMailController.SendMail [notification.Id: {notify.Id} notification.Protocol: {notify.Protocol}]");

                if (Enum.IsDefined(typeof(Protocol), notify.Protocol))
                {
                    switch ((Protocol)Enum.Parse(typeof(Protocol), notify.Protocol, true))
                    {
                    case Protocol.Email:
                        await _smtpService.SendAsync(notify.Receiver, notify.Body, notify.Channel);

                        break;

                    case Protocol.SignalR:
                        await NotificationsHub.SendNotification(notify.Receiver, notify);

                        break;
                    }
                }
                responce = Request.CreateResponse(HttpStatusCode.OK, notify);
            }
            catch (Exception ex)
            {
                _logger.Error($"SendMailController.SendMail [mail.Id: {notify.Id}]", ex);
                responce = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message);
            }
            return(responce);
        }
        public async Task <NotificationDTO> UpdateNotification(NotificationDTO notification)
        {
            var mappedNotification   = _mapper.Map <Notification>(notification);
            var returnedNotification = await _notificationRepository.UpdateNotification(mappedNotification);

            return(_mapper.Map <NotificationDTO>(returnedNotification));
        }
示例#5
0
        public HttpResponseMessage addNotification(NotificationDTO notificationDTO)
        {
            VolunteerMatchDbContext db = new VolunteerMatchDbContext();



            try
            {
                Notification notification = new Notification()
                {
                    memberId         = notificationDTO.memberId,
                    otherMemberId    = notificationDTO.otherMemberId,
                    notificationText = notificationDTO.notificationText,
                    notificationType = notificationDTO.notificationType,
                    unixdate         = notificationDTO.unixdate
                };
                db.Notifications.Add(notification);
                db.SaveChanges();

                return(Request.CreateResponse(HttpStatusCode.OK, "Notification Saved In DB"));
            }
            catch (Exception)
            {
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, "Unknown error occured"));
            }
        }
        public async Task <IActionResult> AddNewNotification([FromBody] NotificationDTO notificationDTO)
        {
            try
            {
                using (loggingHelper.RMTraceManager.StartTrace("WebService.AddNewNotification"))
                {
                    string methodName = MethodHelper.GetActualAsyncMethodName();
                    loggingHelper.Log(methodName + LoggerTraceConstants.COLON + LoggerTraceConstants.MethodExecutionStarted, TraceEventType.Verbose, null, LoggerTraceConstants.Category, LoggerTraceConstants.NotificationAPIPriority, LoggerTraceConstants.NotificationControllerMethodEntryEventId, LoggerTraceConstants.Title);

                    int status = await notificationBusinessService.AddNewNotification(notificationDTO);

                    loggingHelper.Log(methodName + LoggerTraceConstants.COLON + LoggerTraceConstants.MethodExecutionCompleted, TraceEventType.Verbose, null, LoggerTraceConstants.Category, LoggerTraceConstants.NotificationAPIPriority, LoggerTraceConstants.NotificationControllerMethodExitEventId, LoggerTraceConstants.Title);
                    return(Ok(status));
                }
            }
            catch (AggregateException ae)
            {
                foreach (var exception in ae.InnerExceptions)
                {
                    loggingHelper.Log(exception, TraceEventType.Error);
                }

                var realExceptions = ae.Flatten().InnerException;
                throw realExceptions;
            }
        }
        public async Task <IHttpActionResult> PostNotification(NotificationDTO notificationDTO)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            Notification notification = new Notification
            {
                ReceiverId        = notificationDTO.ReceiverId,
                SenderId          = notificationDTO.SenderId,
                Message           = notificationDTO.Message,
                CreatedDate       = DateTime.UtcNow,
                NotificationState = "U",
                RowStatus         = "I",
                Title             = notificationDTO.Title
            };

            db.Configuration.ProxyCreationEnabled = false;
            db.Notifications.Add(notification);
            await db.SaveChangesAsync();

            hub.SendNotification(notificationDTO.ReceiverId.ToString());

            return(Ok(notification.NotificationId));
        }
示例#8
0
        public async Task <NotificationDTO> CreateNotification(NotificationDTO notification)
        {
            notification.Id = GetNewNotifyId();

            _testData.Add(notification);
            return(notification);
        }
示例#9
0
        public async Task DeleteRights(int collaboratorId, int projectId, int currentUserId)
        {
            var project = await _context.Projects.Where(item => item.Id == projectId).FirstOrDefaultAsync();

            if (project.AuthorId == currentUserId)
            {
                var collaborator = await _context.ProjectMembers
                                   .Where(item => item.UserId == collaboratorId && item.ProjectId == projectId)
                                   .FirstOrDefaultAsync();

                _context.ProjectMembers.Remove(collaborator);
                await _context.SaveChangesAsync();
            }
            else
            {
                _logger.LogWarning(LoggingEvents.HaveException, $"NonAuthorRightsChange");
                throw new NonAuthorRightsChange();
            }

            var notification = new NotificationDTO()
            {
                Type      = NotificationType.AssinedToProject,
                ProjectId = projectId,
                DateTime  = DateTime.Now,
                Message   = $"You was deleted from project \"{project.Name}\".",
                Status    = NotificationStatus.Message
            };

            using (var scope = _serviceScopeFactory.CreateScope())
            {
                var notificationService = scope.ServiceProvider.GetService <INotificationService>();
                await notificationService.SendNotificationToUserById(collaboratorId, notification);
            }
        }
        public override async Task HandleMessageAsync(string content)
        {
            // we just print this message
            _logger.LogInformation($"consumer received {content}");

            var buildResult = JsonConvert.DeserializeObject <BuildResultDTO>(content);

            var notification = new NotificationDTO();

            if (buildResult.WasBuildSucceeded)
            {
                notification.Status = NotificationStatus.Message;
            }
            else
            {
                notification.Status = NotificationStatus.Error;
            }
            notification.Message   = $"Build project";
            notification.Type      = NotificationType.ProjectBuild;
            notification.ProjectId = buildResult.ProjectId;
            notification.Metadata  = buildResult.Message;
            notification.DateTime  = DateTime.Now;

            using (var scope = _serviceScopeFactory.CreateScope())
            {
                var notificationService = scope.ServiceProvider.GetService <INotificationService>();
                var buildService        = scope.ServiceProvider.GetService <IBuildService>();
                await notificationService.SendNotificationToProjectParticipants(buildResult.ProjectId, notification);

                await buildService.CreateFinishBuildResult(buildResult, notification.DateTime);
            }
        }
示例#11
0
 public void NewNotification(NotificationDTO notf)
 {
     // Console.WriteLine(mess.receiverId, mess.clientuniqueid);
     //   onlineUsers.Add(mess.senderUsername, mess.clientuniqueid);
     //    Clients.Client(mess.receiverId).SendAsync("MessageReceived", mess);
     Clients.All.SendAsync("NotificationReceived", notf);
 }
示例#12
0
        public void PushMessage(NotificationDTO request)
        {
            //string serverKey = "AAAAY8UVqoU:APA91bHD9ICFvT1CdO-gcHyo4p69tfQfXNJa_dM0Y5JyXrqzezUZt0cG-ax_DOCg-bvDspgUBOTxpRb2IXvOhyiE6o7RBYFMzkVJct65LniMec0LIo8rQF3pMUDybc4gNc8jlcgeAq1D";

            try
            {
                var result  = "-1";
                var webAddr = "https://fcm.googleapis.com/fcm/send";

                var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
                httpWebRequest.ContentType = "application/json";
                httpWebRequest.Headers.Add("Authorization:key=" + ConfigKey.SERVER_KEY);
                httpWebRequest.Method = "POST";
                //string json = "{\"to\": \"c7cOP-6Sn_4:APA91bEaj-PBS5c91p1FiPll08DTzpCZRf3RmOJcqvj4wWQqvB-6OTgrI3n_320lkL-d2rpPkNhtIeSSIX6zS8w287hQabHP8g6Yitv8YhtXAZaQTIz9D3emLyq7MN_GueDyG-qJWZNy\",\"data\": {\"message\": \"This is a Firebase Cloud Messaging Topic Message!\",}}";
                string json = JsonConvert.SerializeObject(request);
                using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                {
                    streamWriter.Write(json);
                    streamWriter.Flush();
                }

                var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    result = streamReader.ReadToEnd();
                }

                // return result;
            }
            catch (Exception ex)
            {
                //  Response.Write(ex.Message);
            }
        }
示例#13
0
        public void SetReaded(bool isDoubleClick)
        {
            NotificationDTO data             = (NotificationDTO)_listView.SelectedObject;
            var             notificationUser = (Katrin.Domain.Impl.NotificationRecipient)_objectSpace.GetOrNew("NotificationRecipient", data.NotificationRecipientId, null);

            if (data.NotificationStatusName != "Readed")
            {
                notificationUser.NotificationStatus = "Readed";
                notificationUser.ReadedOn           = DateTime.Now;
                _objectSpace.SaveChanges();
                data.NotificationStatus     = 0;
                data.NotificationStatusName = "Readed";
                GridView gridView = (GridView)_listView.ObjectGridView;
                gridView.LayoutChanged();
                ReceiveNotification.timer_Elapsed(null, null);
            }
            else if (!isDoubleClick)
            {
                notificationUser.NotificationStatus = "Opened";
                notificationUser.ReadedOn           = DateTime.Now;
                _objectSpace.SaveChanges();
                data.NotificationStatus     = 1;
                data.NotificationStatusName = "Opened";
                GridView gridView = (GridView)_listView.ObjectGridView;
                gridView.LayoutChanged();
                ReceiveNotification.timer_Elapsed(null, null);
            }
        }
示例#14
0
        public async Task DeleteCompanyTask(long taskId)
        {
            var task = await _unitOfWork.BookRepository
                       .Query
                       .Include(b => b.Company)
                       .Include(b => b.Vendor)
                       .Include(b => b.Vendor.Person)
                       .Include(b => b.Vendor.Person.Account)
                       .Include(b => b.Work)
                       .Where(b => b.Id == taskId)
                       .SingleOrDefaultAsync();

            task.ParentBookId = 0;
            _unitOfWork.BookRepository.Update(task);
            await _unitOfWork.SaveAsync();

            /* Send Notification */
            var notification = new NotificationDTO()
            {
                Title        = $"New order for {task.Work.Name}",
                Description  = $"{task.Company.Name} deleted your task {task.Work.Name}.",
                SourceItemId = task.Id,
                Time         = DateTime.Now,
                Type         = NotificationType.TaskNotification
            };
            var receiverId = task.Vendor.Person.Account.Id;
            await _notificationService.CreateAsync(receiverId, notification);
        }
示例#15
0
        /// <summary>
        /// Get the notification details based on the UDPRN
        /// </summary>
        /// <param name="uDPRN">UDPRN id</param>
        /// <returns>NotificationDTO object</returns>
        public async Task<NotificationDTO> GetNotificationByUDPRN(int uDPRN)
        {
            using (loggingHelper.RMTraceManager.StartTrace("Business.GetNotificationByUDPRN"))
            {
                NotificationDTO notificationDTO = null;
                string methodName = MethodHelper.GetActualAsyncMethodName();
                loggingHelper.Log(methodName + LoggerTraceConstants.COLON + LoggerTraceConstants.MethodExecutionStarted, TraceEventType.Verbose, null, LoggerTraceConstants.Category, LoggerTraceConstants.NotificationAPIPriority, LoggerTraceConstants.NotificationBusinessServiceMethodEntryEventId, LoggerTraceConstants.Title);
                var getNotificationByUDPRN = await notificationDataService.GetNotificationByUDPRN(uDPRN);
                if (getNotificationByUDPRN != null)
                {
                    notificationDTO = new NotificationDTO
                    {
                        ID = getNotificationByUDPRN.ID,
                        Notification_Heading = getNotificationByUDPRN.Notification_Heading,
                        Notification_Message = getNotificationByUDPRN.Notification_Message,
                        NotificationDueDate = getNotificationByUDPRN.NotificationDueDate,
                        NotificationActionLink = getNotificationByUDPRN.NotificationActionLink,
                        NotificationSource = getNotificationByUDPRN.NotificationSource,
                        PostcodeDistrict = getNotificationByUDPRN.PostcodeDistrict,
                        PostcodeSector = getNotificationByUDPRN.PostcodeSector,
                        NotificationType_GUID = getNotificationByUDPRN.NotificationTypeGUID,
                        NotificationPriority_GUID = getNotificationByUDPRN.NotificationPriorityGUID
                    };
                }

                loggingHelper.Log(methodName + LoggerTraceConstants.COLON + LoggerTraceConstants.MethodExecutionCompleted, TraceEventType.Verbose, null, LoggerTraceConstants.Category, LoggerTraceConstants.NotificationAPIPriority, LoggerTraceConstants.NotificationBusinessServiceMethodExitEventId, LoggerTraceConstants.Title);
                return notificationDTO;
            }
        }
示例#16
0
        public HttpResponseMessage ViewJournal(NotificationDTO postData)
        {
            try
            {
                var notification = NotificationsController.Instance.GetNotification(postData.NotificationId);

                if (notification != null && notification.Context != null && notification.Context.Contains("_"))
                {
                    //Dismiss the notification
                    NotificationsController.Instance.DeleteNotificationRecipient(postData.NotificationId, UserInfo.UserID);

                    var context   = notification.Context.Split('_');
                    var userId    = Convert.ToInt32(context[0]);
                    var journalId = Convert.ToInt32(context[1]);
                    var ji        = JournalController.Instance.GetJournalItem(PortalSettings.PortalId, userId, journalId);
                    if (ji.ProfileId != Null.NullInteger)
                    {
                        return(Request.CreateResponse(HttpStatusCode.OK, new { Result = "success", Link = Globals.UserProfileURL(ji.ProfileId) }));
                    }

                    return(Request.CreateResponse(HttpStatusCode.OK, new { Result = "success", Link = Globals.UserProfileURL(userId) }));
                }
            }
            catch (Exception exc)
            {
                Logger.Error(exc);
            }

            return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "unable to process notification"));
        }
        private string sendNotification(User user, NotificationDTO notification)
        {
            RestClient client = new RestClient();

            client.BaseUrl = new Uri(PushBulletService.PUSH_BULLET_API_URL);

            RestRequest request = new RestRequest();

            Push push = new Push()
            {
                type  = PushBulletService.PUSH_BULLET_PUSH_TYPE_NOTE,
                body  = notification.Body,
                title = notification.Title
            };

            request.AddJsonBody(push);
            request.AddHeader(PushBulletService.PUSH_BULLET_ACCESS_TOKEN_HEADER, user.AccessToken);

            var result = client.Post <dynamic>(request);

            if (result.StatusCode == System.Net.HttpStatusCode.OK)
            {
                return(result.Data[PushBulletService.PUSH_BULLET_IDENTITY_ATTR]);
            }
            else
            {
                throw new PushBulletException(String.Format("Error calling PushBullet: {0}", result.Data["error"]["message"]));
            }
        }
示例#18
0
        public async Task <List <NotificationDTO> > GetAllUserNewNotifications(Guid userId)
        {
            var notifications = await ServiceUnitOfWork.NotificationRepository.GetNewNotifications(userId);

            var notificationDtos = new List <NotificationDTO>();

            foreach (var not in notifications)
            {
                var training = await ServiceUnitOfWork.TrainingRepository.FindAsync(not.TrainingId);

                var trainingDto = new TrainingDTO
                {
                    Id           = training.Id,
                    TrainingDate = training.Start,
                    StartTime    = training.StartTime,
                    Description  = training.Description
                };
                var notDto = new NotificationDTO
                {
                    Id = not.Id,
                    NotificationContent = not.Content,
                    Recieved            = not.Recived,
                    Title       = not.Title,
                    TrainingDto = trainingDto
                };
                notificationDtos.Add(notDto);
            }

            return(notificationDtos);
        }
示例#19
0
        public async Task RemoveMessage(long messageId)
        {
            var mes = await _unitOfWork.ChatMessageRepository.GetByIdAsync(messageId);

            var notification = new NotificationDTO()
            {
                Title        = $"Some messages were deleted",
                Description  = $"Some messages were deleted",
                SourceItemId = messageId,
                Time         = DateTime.Now,
                Type         = NotificationType.ChatNotification
            };

            _unitOfWork.ChatMessageRepository.Delete(messageId);
            long receiverId;

            if (mes.Dialog.Participant1.Id != mes.Owner.Id)
            {
                receiverId = mes.Dialog.Participant1.Id;
            }
            else
            {
                receiverId = mes.Dialog.Participant2.Id;
            };
            await _notificationService.CreateDelAsync(receiverId, mes.Dialog.Id);

            await _unitOfWork.SaveAsync();
        }
        public NotificationDTO Send(string username, NotificationDTO notification)
        {
            User user = userService.Get(username);

            notification.PushBulletId = this.sendNotification(user, notification);
            return(notification);
        }
示例#21
0
        public async Task <ActionResult> CustomerSetExecutorForIndent(UserActivityViewModel activityModel)
        {
            var clientId = Session["Id"];

            if (clientId == null)
            {
                return(RedirectToAction("Registration", "Customer"));
            }

            int    customerId   = Convert.ToInt32(clientId);
            string customerName = Session["Name"].ToString();

            IndentDTO indentDTO = new IndentDTO()
            {
                IndentId = activityModel.IndentId
            };
            await _userActivityService.SaveExecutorForIndent(indentDTO, activityModel.UserOpponentId);

            string    cacheKey     = "show-indent-" + activityModel.IndentId.ToString();
            IndentDTO cachedIndent = HttpContext.Cache[cacheKey] as IndentDTO;

            if (cachedIndent != null)
            {
                HttpContext.Cache.Remove(cacheKey);
            }

            NotificationDTO notificationDTO = GenerateNotification(activityModel, Role.Executor, "Сandidature confirmed");

            notificationDTO.FromId   = customerId;
            notificationDTO.FromName = customerName;

            await _userActivityService.SaveNotification(notificationDTO);

            return(RedirectToAction("ShowIndent", "Indent", new { id = activityModel.IndentId }));
        }
示例#22
0
        public List <NotificationDTO> FindAll()
        {
            try
            {
                this.OpenConnection();

                var dbCmd = this.db.CreateCommand();
                dbCmd.CommandText = "SELECT * FROM Notifications";
                IDataReader result = dbCmd.ExecuteReader();

                List <NotificationDTO> notifications = new List <NotificationDTO>();

                while (result.Read())
                {
                    var notification = new NotificationDTO
                    {
                        Id      = (int)result["Id"],
                        Message = result["Message"].ToString(),
                    };

                    notifications.Add(notification);
                }

                return(notifications);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
            finally
            {
                this.CloseConnection();
            }
        }
        public HttpResponseMessage ViewJournal(NotificationDTO postData)
        {
            try
            {
                var notification = NotificationsController.Instance.GetNotification(postData.NotificationId);

                if(notification != null && notification.Context != null && notification.Context.Contains("_"))
                {
                    //Dismiss the notification
                    NotificationsController.Instance.DeleteNotificationRecipient(postData.NotificationId, UserInfo.UserID);

                    var context = notification.Context.Split('_');
                    var userId = Convert.ToInt32(context[0]);
                    var journalId = Convert.ToInt32(context[1]);
                    var ji = JournalController.Instance.GetJournalItem(PortalSettings.PortalId, userId, journalId);
                    if (ji.ProfileId != Null.NullInteger)
                    {
                        return Request.CreateResponse(HttpStatusCode.OK, new { Result = "success", Link = Globals.UserProfileURL(ji.ProfileId) });
                    }

                    return Request.CreateResponse(HttpStatusCode.OK, new { Result = "success", Link = Globals.UserProfileURL(userId) });
                }
            }
            catch (Exception exc)
            {
                Logger.Error(exc);
            }

            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "unable to process notification");
        }
示例#24
0
        public NotificationDTO Find(int id)
        {
            try
            {
                this.OpenConnection();

                var dbCmd = this.db.CreateCommand();
                dbCmd.CommandText = $"SELECT * FROM Notifications WHERE Id = {id}";
                IDataReader result = dbCmd.ExecuteReader();

                var notification = new NotificationDTO();

                while (result.Read())
                {
                    notification.Id      = (int)result["Id"];
                    notification.Message = result["Message"].ToString();
                }

                return(notification);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
            finally
            {
                this.CloseConnection();
            }
        }
示例#25
0
        protected override void OnResume()
        {
            base.OnResume();
            if (Intent?.Extras != null)
            {
                try
                {
                    string data = Intent?.Extras.GetString("data");
                    if (data != null)
                    {
                        Intent.RemoveExtra("data");

                        NotificationDTO notification         = JsonConvert.DeserializeObject <NotificationDTO>(data);
                        string          NotificationSentTime = Intent.Extras.GetString("NotificationSentTime");
                        notification.NotificationSentTime = DateTime.Parse(NotificationSentTime);

                        if (!DataBase.Instance.Query <NotificationDTO>().Any(x => x.NotificationID == notification.NotificationID))
                        {
                            if (notification.NotificationType == NotificationsTypesEnum.Order)
                            {
                                notification.IsOrderPending = true;
                            }

                            DataBase.Instance.Add(notification);
                        }

                        NavigateNotification(notification.NotificationType, notification.NotificationID);
                    }
                    else
                    {
                        string NotificationID = Intent.Extras.GetString("notificationID");
                        NotificationsTypesEnum NotificationType = (NotificationsTypesEnum)Enum.Parse(typeof(NotificationsTypesEnum), Intent.Extras.GetString("notificationType"), true);
                        if (!string.IsNullOrEmpty(NotificationID))
                        {
                            if (DataBase.Instance.Query <NotificationDTO>().FirstOrDefault(x => x.NotificationID == int.Parse(NotificationID)) != null)
                            {
                                string NotificationSentTime = Intent.Extras.GetString("notificationSentTime");
                                string NotificationTitle    = Intent.Extras.GetString("notificationTitle");
                                string NotificationBody     = Intent.Extras.GetString("notificationBody");

                                DataBase.Instance.Add(new NotificationDTO()
                                {
                                    NotificationID       = int.Parse(NotificationID),
                                    NotificationBody     = NotificationBody,
                                    NotificationSentTime = DateTime.Parse(NotificationSentTime),
                                    NotificationTitle    = Title,
                                    NotificationType     = NotificationType,
                                    IsOrderPending       = NotificationType == NotificationsTypesEnum.Order ? true : false
                                });
                            }
                        }
                        NavigateNotification(NotificationType, int.Parse(NotificationID));
                    }
                }
                catch (Exception)
                {
                    //Exception ?
                }
            }
        }
示例#26
0
        public async Task <NotificationDTO> Edit(NotificationDTO dto)
        {
            var notification = dto.MapTo <TNotification>();
            await notificationRepository.Edit(notification, Session);

            return(notification.MapTo <NotificationDTO>());
        }
示例#27
0
        /// <summary>
        /// Create the notification.
        /// </summary>
        /// <param name="notification">Notification.</param>
        /// <returns>int</returns>
        public async Task <NotificationDTO> CreateNotification(NotificationDTO notification)
        {
            using (var context = new NotificationsContext())
            {
                var newNotification = new Notification
                {
                    Id          = notification.Id,
                    Channel     = notification.Channel,
                    Receiver    = notification.Receiver,
                    Type        = notification.Type,
                    Title       = notification.Title,
                    Body        = notification.Body,
                    IsReaded    = notification.IsReaded,
                    CreatedDate = DateTime.Now,
                    Protocol    = notification.Protocol
                };

                context.Notifications.Add(newNotification);

                await context.SaveChangesAsync();

                notification.Id          = newNotification.Id;
                notification.CreatedDate = newNotification.CreatedDate;

                return(notification);
            }
        }
示例#28
0
        public async Task CreateAsync(long accountId, NotificationDTO notificationDto)
        {
            var notification = CreateNotification(accountId, notificationDto);

            _unitOfWork.NotificationRepository.Query
            .Where(n => !n.IsDeleted && !n.IsViewed && n.Type == NotificationType.ChatNotification)
            .ToList()
            .ForEach(n =>
            {
                n.IsViewed = true;
                _unitOfWork.NotificationRepository.Update(n);
            });

            _unitOfWork.NotificationRepository.Create(notification);
            await _unitOfWork.SaveAsync();

            switch (notification.Type)
            {
            case NotificationType.TaskNotification:
                await _proxy.RefreshOrdersForAccount(accountId);

                break;
            }

            notificationDto.Id = notification.Id;
            await _proxy.SendNotification(accountId, notificationDto);
        }
示例#29
0
        /// <summary>
        /// Add new notification to the database
        /// </summary>
        /// <param name="notificationDTO">NotificationDTO object</param>
        /// <returns>Task<int></returns>
        public async Task<int> AddNewNotification(NotificationDTO notificationDTO)
        {
            using (loggingHelper.RMTraceManager.StartTrace("Business.AddNewNotification"))
            {
                string methodName = MethodHelper.GetActualAsyncMethodName();
                loggingHelper.Log(methodName + LoggerTraceConstants.COLON + LoggerTraceConstants.MethodExecutionStarted, TraceEventType.Verbose, null, LoggerTraceConstants.Category, LoggerTraceConstants.NotificationAPIPriority, LoggerTraceConstants.NotificationBusinessServiceMethodEntryEventId, LoggerTraceConstants.Title);

                try
                {
                    NotificationDataDTO notificationDataDTO = new NotificationDataDTO
                    {
                        ID = notificationDTO.ID,
                        Notification_Heading = notificationDTO.Notification_Heading,
                        Notification_Message = notificationDTO.Notification_Message,
                        NotificationDueDate = notificationDTO.NotificationDueDate,
                        NotificationActionLink = notificationDTO.NotificationActionLink,
                        NotificationSource = notificationDTO.NotificationSource,
                        PostcodeDistrict = notificationDTO.PostcodeDistrict,
                        PostcodeSector = notificationDTO.PostcodeSector,
                        NotificationTypeGUID = notificationDTO.NotificationType_GUID,
                        NotificationPriorityGUID = notificationDTO.NotificationPriority_GUID
                    };

                    return await notificationDataService.AddNewNotification(notificationDataDTO);
                }
                finally
                {
                    loggingHelper.Log(methodName + LoggerTraceConstants.COLON + LoggerTraceConstants.MethodExecutionCompleted, TraceEventType.Verbose, null, LoggerTraceConstants.Category, LoggerTraceConstants.NotificationAPIPriority, LoggerTraceConstants.NotificationBusinessServiceMethodExitEventId, LoggerTraceConstants.Title);
                }
            }
        }
        private static string createEmailBody(NotificationDTO notification, string action)
        {
            string body         = string.Empty;
            var    templateName = ((EnumNotificationType)notification.NotificationType).ToString("g");

            using (StreamReader reader = new StreamReader(HttpContext.Current.Server.MapPath(String.Format("{0}{1}.html", "~/Content/MailTemplates/", templateName))))
            {
                body = reader.ReadToEnd();
            }
            if (notification.NotificationType == (int)EnumNotificationType.DecisionExecution || notification.NotificationType == (int)EnumNotificationType.DecsionForInform)
            {
                body = body.Replace("{DecisionSubject}", notification.Decision.Subject);
                body = body.Replace("{DecisionLink}", String.Format("{0}/{1}", ConfigurationManager.AppSettings["SystemURl"], "/home/viewDecision/" + notification.Decision.Id));
                body = body.Replace("{DecisionNO}", notification.Decision.Id.ToString());
                body = body.Replace("{DecisionDate}", notification.Decision.ExecutionDate.ToString());
                body = body.Replace("{Action}", action);
            }
            else if (notification.NotificationType == (int)EnumNotificationType.MeetingRequest)
            {
                body = body.Replace("{meetingNo}", notification.Meeting.MeetingNumber.ToString());
                body = body.Replace("{meetingDate}", notification.Meeting.MeetingDate.ToLongDateString());
                body = body.Replace("{meetingTime}", notification.Meeting.MeetingDate.ToShortTimeString());
                body = body.Replace("{DecisionLink}", String.Format("{0}/{1}", ConfigurationManager.AppSettings["SystemURl"], "/home/viewMeeting/" + notification.MeetingId));
            }
            return(body);
        }
示例#31
0
        public void Update(NotificationDTO notification)
        {
            try
            {
                this.OpenConnection();

                var dbCmd = this.db.CreateCommand();
                dbCmd.CommandText = "UPDATE Notifications SET Message=@message WHERE Id=@id";

                IDbDataParameter paramMessage = new SqlParameter("message", notification.Message);
                dbCmd.Parameters.Add(paramMessage);

                IDbDataParameter paramId = new SqlParameter("id", notification.Id);
                dbCmd.Parameters.Add(paramId);

                dbCmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
            finally
            {
                this.CloseConnection();
            }
        }
        public HttpResponseMessage ApproveGroup(NotificationDTO postData)
        {
            try
            {
                var recipient = InternalMessagingController.Instance.GetMessageRecipient(postData.NotificationId, UserInfo.UserID);
                if (recipient == null) return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unable to locate recipient");

                var notification = NotificationsController.Instance.GetNotification(postData.NotificationId);
                ParseKey(notification.Context);
                if (_roleInfo == null)
                {
                    return  Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unable to locate role");
                }
                if (!IsMod())
                {
                    return Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Not Authorized!");
                }
                var roleController = new RoleController();
                _roleInfo.Status = RoleStatus.Approved;
                roleController.UpdateRole(_roleInfo);
                var roleCreator = UserController.GetUserById(PortalSettings.PortalId, _roleInfo.CreatedByUserID);
                //Update the original creator's role
                roleController.UpdateUserRole(PortalSettings.PortalId, roleCreator.UserID, _roleInfo.RoleID, RoleStatus.Approved, true, false);
                GroupUtilities.CreateJournalEntry(_roleInfo, roleCreator);

                var notifications = new Notifications();
                var siteAdmin = UserController.GetUserById(PortalSettings.PortalId, PortalSettings.AdministratorId);
                notifications.AddGroupNotification(Constants.GroupApprovedNotification, _tabId, _moduleId, _roleInfo, siteAdmin, new List<RoleInfo> { _roleInfo });
                NotificationsController.Instance.DeleteAllNotificationRecipients(postData.NotificationId);

                return Request.CreateResponse(HttpStatusCode.OK, new {Result = "success"});
            }
            catch (Exception exc)
            {
                Logger.Error(exc);
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc);
            }
        }
        public HttpResponseMessage RejectGroup(NotificationDTO postData)
        {
            try
            {
                var recipient = InternalMessagingController.Instance.GetMessageRecipient(postData.NotificationId, UserInfo.UserID);
                if (recipient == null) return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unable to locate recipient");

                var notification = NotificationsController.Instance.GetNotification(postData.NotificationId);
                ParseKey(notification.Context);
                if (_roleInfo == null)
                {
                    return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unable to locate role");
                }
                if (!IsMod())
                {
                    return Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Not Authorized!");
                }
                var notifications = new Notifications();
                var roleCreator = UserController.GetUserById(PortalSettings.PortalId, _roleInfo.CreatedByUserID);
                var siteAdmin = UserController.GetUserById(PortalSettings.PortalId, PortalSettings.AdministratorId);
                notifications.AddGroupNotification(Constants.GroupRejectedNotification, _tabId, _moduleId, _roleInfo, siteAdmin, new List<RoleInfo> { _roleInfo }, roleCreator);

                var role = RoleController.Instance.GetRole(PortalSettings.PortalId, r => r.RoleID == _roleId);
                RoleController.Instance.DeleteRole(role);
                NotificationsController.Instance.DeleteAllNotificationRecipients(postData.NotificationId);
                return Request.CreateResponse(HttpStatusCode.OK, new {Result = "success"});
            }
            catch (Exception exc)
            {
                Logger.Error(exc);
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc);
            }
        }
        public HttpResponseMessage RejectMember(NotificationDTO postData)
        {
            try
            {
                var recipient = InternalMessagingController.Instance.GetMessageRecipient(postData.NotificationId, UserInfo.UserID);
                if (recipient == null) return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unable to locate recipient");

                var notification = NotificationsController.Instance.GetNotification(postData.NotificationId);
                ParseKey(notification.Context);
                if (_memberId <= 0)
                {
                    return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unable to locate Member");
                }
                if (_roleInfo == null)
                {
                    return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unable to locate Role");
                }

                var member = UserController.GetUserById(PortalSettings.PortalId, _memberId);



                if (member != null)
                {
                    RoleController.DeleteUserRole(member, _roleInfo, PortalSettings, false) ;
                    var notifications = new Notifications();
                    var groupOwner = UserController.GetUserById(PortalSettings.PortalId, _roleInfo.CreatedByUserID);
                    notifications.AddMemberNotification(Constants.MemberRejectedNotification, _tabId, _moduleId, _roleInfo, groupOwner, member);
                    NotificationsController.Instance.DeleteAllNotificationRecipients(postData.NotificationId);

                    return Request.CreateResponse(HttpStatusCode.OK, new {Result = "success"});
                }
            } catch (Exception exc)
            {
                Logger.Error(exc);
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc);
            }

            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unknown Error");
        }